Home > Blockchain >  moment js not showing local time it's showing same in the Database
moment js not showing local time it's showing same in the Database

Time:12-04

how to display createdAt field date according to the local timezone. i have tried it's only working for localhost when I upload it on the server it's showing createdAt field data UTC format.

here is my code

dateFormatwithSec(date_time) {

    const testDateUtc = moment.utc(date_time);
    const localDate = moment(testDateUtc).local();
    return localDate.format('YYYY-MM-DD HH:mm:ss');
},

why it's not providing the right output on the server.

CodePudding user response:

This isn't an answer, it's really an extended comment. The OP should include an example date_time string, the actual output and the expected output in the OP, not in comments.

Until that is known, no one can understand what "it's not providing the right output on the server" means.

Here is an explanation of what is happening, hopefully it helps.

Moment's utc method causes it to display timestamps as UTC. For parsing, it causes it to use UTC only if there is no offset in the timestamp. So given a timestamp like "2021-12-02 15:15:33" it will return a moment object with a Date that has a time value equivalent to 2021-12-02T15:15:33 00:00.

The local method causes moment to display the date in the local timezone. Note that "local" means according to system settings, not the actual location of the system.

Consider the following, where the Z token has been added to display the offset that moment is using for the objects:

function dateFormatwithSec (date_time) {

  // Set moment to UTC mode and parse the input string as UTC
  let testDateUtc = moment.utc(date_time);
  console.log('testDateUtc: '   testDateUtc.format('YYYY-MM-DD HH:mm:ss Z'));

  // Set the moment object to local mode and return a formatted date
  let localDate = moment(testDateUtc).local();
  return localDate.format('YYYY-MM-DD HH:mm:ss Z');
}

let ts = '2021-12-02 15:15:33 04:00';
console.log('localDate  : '  dateFormatwithSec(ts));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

PS. When parsing strings, it's always best to also supply the format, so:

moment.utc(date_time, 'YYYY-MM-DD HH:mm:ss')

is preferred. It also allows maintainers to see the expected format (though it should be in the documentation too). Even very small changes to the format will cause moment to fall back to the implementation's built–in parser, e.g. '2021-12-02 15:15:33 04:00' vs '2021-12-02 15:15:33 04:00'.

  • Related