Reputation: 1953
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?
Upvotes: 3
Views: 10154
Reputation: 31482
Your 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.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
Upvotes: 3
Reputation: 3451
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.
Upvotes: 1
Reputation: 1868
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
Upvotes: 0
Reputation: 1454
Look this link https://www.w3schools.com/js/js_date_formats.asp , paragraph 'ISO Dates'
Omitting T or Z in a date-time string can give different result in different browser.
Upvotes: 0