0

Hi I have generated a Unix Time Stamp with an online generator and I choose that Date:

01/12/2020 @ 9:30pm (UTC)

Which gave me result: 1578864600

I want to display it now in my react app: (date is my result above)

const timestamp = new Date().setMilliseconds(date);
  const formattedDate = new Intl.DateTimeFormat('pl-PL', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    weekday: 'long',
    hour: 'numeric',
    minute: 'numeric',
  }).format(timestamp);

But in my react app I am getting that wrong Date:

Tuesday, 14.01.2020, 17:07

Why it is calculating it wrong??

Freestyle09
  • 4,894
  • 8
  • 52
  • 83
  • In which format you want the output to be in? – Prabhjot Singh Kainth Dec 27 '19 at 09:43
  • `1578864600` doesn't seem right at all, and `new Date().setMilliseconds(date);` is not the correct way to construct a date from a timestamp. Edit: ah, unix timestamp websites give seconds, not milliseconds? You are missing three zeroes: `new Date(1578864600000);` - results in `"niedziela, 12.01.2020, 22:30"` with the code you've given. – ASDFGerte Dec 27 '19 at 09:44
  • Unix timestamp is the number of seconds from 1. January 1970. You are creating a new Javascript DateTime object with the current date and than add several days with the setMilliseconds() function. To convert Unix timestamp to Javascript DateTime check this Stack Overflow answer: from unix timestamp to datetime – Erik Müller Dec 27 '19 at 09:57
  • Please fix link – Freestyle09 Dec 27 '19 at 10:00
  • @ASDFGerte but I wanted 21:30 why It returns 22:30? – Freestyle09 Dec 27 '19 at 10:01
  • 2
    timezone probably? The timestamp you give above is in UTC. E.g. `new Date(1578864600000).toISOString();` yields `"2020-01-12T21:30:00.000Z"`, so yeah, it's a timezone issue. – ASDFGerte Dec 27 '19 at 10:02
  • It looks like `Intl.DateTimeFormat` has an option for timezone, and UTC must always be available, so just use that. – ASDFGerte Dec 27 '19 at 10:07
  • Yes, I have changed that to Europe/London and it shows the correct result, I have created new object new Date(date * 1000) and now works well – Freestyle09 Dec 27 '19 at 10:08
  • https://github.com/formatjs/react-intl/blob/master/examples/TimeZone.tsx – JGFMK Dec 27 '19 at 10:21

0 Answers0