I have a date in format dd.MM.yyyy HH:mm:ss
and I need to convert it to ISO format, but it's not working correctly.
Here is my code:
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'dd.MM.yyyy HH:mm:ss')
console.log(parsedDate.toISOString()); //result is 2016-12-31T23:00:00.000Z
example2:
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = new Date(date)
console.log(parsedDate.toISOString()); //result is 2016-11-30T23:00:00.000Z
Where is the problem? Why do I get different results?
I have a date in format dd.MM.yyyy HH:mm:ss
and I need to convert it to ISO format, but it's not working correctly.
Here is my code:
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'dd.MM.yyyy HH:mm:ss')
console.log(parsedDate.toISOString()); //result is 2016-12-31T23:00:00.000Z
example2:
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = new Date(date)
console.log(parsedDate.toISOString()); //result is 2016-11-30T23:00:00.000Z
Where is the problem? Why do I get different results?
Share Improve this question edited Oct 25, 2017 at 11:39 user7605325 asked Oct 25, 2017 at 11:37 bluraybluray 1,9636 gold badges40 silver badges73 bronze badges 1- Think about the timezone you're in vs GMT. For me, someone living in the GMT timezone, this code works correctly. --- The second example, the first reports the wrong year. – evolutionxbox Commented Oct 25, 2017 at 11:43
4 Answers
Reset to default 3Your format parameter is wrong, use 'DD.MM.YYYY H:mm:ss'
instead.
There is no lowercase dd
, use uppercase DD
for day of month and use uppercase YYYY
for year instead of lowercase yyyy
.
Please note that toISOString()
:
Note that
.toISOString()
always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()
, as outlined in the ES2015 specification.
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.19.1/moment.min.js"></script>
I just tried using moment.js and it seems you used a mask as you'd use in C# for example. Moment.js uses capitals in the date parts.
let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'DD.MM.YYYY HH:mm:ss');
console.log(parsedDate.toISOString()); //result is 2016-01-11T23:00:00.000Z
The Date.parse()
function requires another kind of input.
Look this link https://www.w3schools./js/js_date_formats.asp , paragraph 'ISO Dates'
Omitting T or Z in a date-time string can give different result in different browser.
In the second example, the parsed date results in December 1, 2016 0:00:00 (GMT+1)
When you output toISOString() it gives you the GMT time, which is 1 hour earlier, hence the November 30, 2016 23:00:00