This is closed question.
Here is code
const dateStr = '1989-11-11T03:34';
let date = new Date(dateStr);
console.log(date.toUTCString());
console.log( date);
And output:
Fri, 10 Nov 1989 22:34:00 GMT
626740440000 <--- far future
Why unix time is in far future?
Here is Playcode link
Solution
The unix timestamp is in milliseconds. Very sad, but I forgot about this(((
CodePudding user response:
It's not wrong.
You seem to have two issues with what you're getting:
- The time isn't the same in your
toISOString
output. - The number you're getting from
date
isn't what you expect.
But both are correct:
- The string has no timezone indicator on it, so since it's a date time string, it's parsed as local time. This is covered by the Date Time String Format section of the specification. But your output is showing GMT (because
toISOString
uses GMT). 626740440000
is the number of milliseconds since The Epoch, not seconds as it was in the original Unix epoch scheme. This is covered by the Time Values and Time Range section of the specification.
If you want to parse your string as UTC (loosely, GMT), add a Z
to the end of it indicating that't is in GMT.
If you want the number of seconds since The Epoch, divide date
by 1000
(perhaps rounding or flooring the result).
CodePudding user response:
the issue with the code is that the input date string does not include a timezone offset. As a result, the Date object that is created using this string will be interpreted as a local time, rather than a UTC time.
To fix this issue, you can either include a timezone offset in the input date string (e.g. '1989-11-11T03:34 00:00'), or you can use the Date.UTC() method to create a Date object that represents a UTC time.
For example:
const dateStr = '1989-11-11T03:34 00:00';
let date = new Date(dateStr);
console.log(date.toUTCString());
console.log( date);
// or
const year = 1989;
const month = 11;
const day = 11;
const hours = 3;
const minutes = 34;
const date = new Date(Date.UTC(year, month, day, hours, minutes));
console.log(date.toUTCString());
console.log( date);