Convert ISO Date string to date in JavaScript - javascript

Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use new Date(dateString) to convert Date, the result is wrong:
var date = new Date("2016-01-23T22:23:32.927");
The result is: Sun Jan 24 2016 05:23:32 GMT+0700. It's not true. I want the date is 23 not 24.
Please help me. Thanks a lot!

You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.

JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.
So what happened:
The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
When you then output the date (I'll assume with console.log), it is converted to the timezone of your environment. In this case 7 hours where added.
If that doesn't suit you, you can change the way you output the date. This depends on what output you want, e.g.:
If you just want the UTC timezone again, you can use date.toISOString().
If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.

If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.
To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:
var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output: Sat Jan 23 2016 22:23:32 GMT-0500
...i.e. your desired result :)
Here's a jsfiddle demonstrating this.

Use date.toUTCString()
it'll give you 23 instead of 24 as it Convert a date object to a string, according to universal time

Related

moment-timezones.js, how to convert date in spesific timezone to utc, disregarding my local timezone?

my system uses timezone UTC+03:00 ,
im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York")
.tz("Z").toDate();
doesnt work correctly
how am i even suppose to convert to utc time?
-----------edit---------------
i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:
moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York").tz("Africa/Accra")
but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!
is there a way to set the utc offset to 0 in momentjs-timezones?
As Álvaro González mentioned, that Date object does not contain Time zone information.
I do the following:
new Date(moment.tz(date, currentTimezone).tz(newTimezone).format('YYYY/MM/DD HH:mm:ss'))
where date is a date object or a string (e.g. '2017-10-30 16:30:00.0000')
so, I change date from currentTimezone to newTimezone and after that new Date object will be returned
Let's change '2017-10-30 16:30:00.0000' from UTC to America/Toronto (UTC-4)
new Date(moment.tz(date, 'UTC').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
And I got
Mon Oct 30 2017 12:30:00 GMT+0400
GMT+0400 is my timezone and console.log() just shows it with any
date object and it can mislead you. Please, don't look at the this
timezone.
Let's change '2017-10-30 16:30:00.0000' from Europe/Samara (UTC+4) to America/Toronto (UTC-4)
new Date(moment.tz('2017-10-30 16:30:00.0000', 'Europe/Samara').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
Firstly, moment.tz undertands that date has no timezone information and associate with Europe/Samara (UTC+4)
timezone. After that computes difference between new and old
timezone (it's -8 hours in this case)
And returns result
Mon Oct 30 2017 08:30:00 GMT+0400
And answer on your question
If xsltDate is a date object or string which do not contain timezone information
dateUTC = new Date(moment.tz(xlsxDate, "America/New_York").tz("UTC").format('YYYY/MM/DD HH:mm:ss'));
If xsltDate contain timezone information (e.g.'2013-06-01T00:00:00-04:00'), then no need to tell moment.tz which timezone xlsxDate has, just mention a new timezone
dateUTC = new Date(moment.tz(xlsxDate, "UTC").format('YYYY/MM/DD HH:mm:ss'));
Short answer is that you cannot.
The .toDate() method of the Moment library returns a native Date object. Such objects do not keep memory of any specific time zone (that's one of the reasons to use Moment in the first place), they just keep track of the exact time moment represented and merely pick a time zone when formatting to string, which is either UTC or the browser's time zone (not an arbitrary one).
The long answer is that you're probably getting correct results but are printing them with a method that uses the browser's time zone.
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.
(i also had to explicitly write the date string format correctly, thanks VincenzoC)
this is the code i was trying to write:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();
however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.toDate();
and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)

How can I create a Date from string, ignoring any timezone offsets?

The server uses +03:00 timezone. It offers me a date in this format: "2017-04-12T00:00:00+03:00"
I then create a new Date from this string:
options.startDate = new Date("2017-04-12T00:00:00+03:00")
But because on the client there is a different timezone, the result is actually:
Tue Apr 11 2017 23:00:00 GMT+0200 (Central Europe Daylight Time)
This brings me back one day and it's a big deal for me. Is there an elegant way to avoid this and create the same Date and Time in javascript, ignoring the timezone offset?
The date you have in options.startDate is the correct one. What you want is to display it as if you were from the same timezone as the server.
If you now server's timezone in the client script then I would considere using a library like moment.js. It would allow you to format date in the timezone you want (GMT for instance, or the one of the server).
Using both moment.js and its plugin timezone code could be :
moment("2017-04-12T00:00:00+03:00").tz("America/Los_Angeles").format();
You should never use the Date constructor or Date.parse to parse strings due to browsers differences. Even if you remove the timezone from the string and parse the remainder, e.g.
console.log( new Date('2017-04-12T00:00:00+03:00'.substr(0,19)).toString() );
you'll get different results in different browsers (e.g. Firefox and Safari).
If you don't want to use a library, use a simple function (see below). However, if you remove the timezone, the string will represent a different moment in time in each timezone with a different offset.
function parseISOIgnoreTimezone(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
console.log(parseISOIgnoreTimezone('2017-04-12T00:00:00+03:00').toString());
I really recommend #VictorDrouin his answer.
But if for some reason you don't want moment.js or fiddle around with it you can use this 'hack'
new Date("2017-04-12T00:00:00+03:00".match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop());
What it does it matches the date against given regex date format, and then supplies it to the date parser which makes it a date.
Be careful when supplying it back to the database that you supply it back without timezone offset.
var stringdate = "2017-04-12T00:00:00+03:00";
function getDate(str_date) {
var matched = str_date.match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop();
return new Date(matched);
}
console.log(getDate(stringdate));

JavaScript displaying correct date from dates stored as UTC on server

I have dates stored in my database in UTC format and calling
element.createdDate = new Date(element.createdDate.toString());
results in displaying the wrong date.
calling
element.createdDate = new Date(element.createdDate.toUTCString());
returns nothing. How do I go about displaying the correct time from UTC?
It appears that your json response contains a string valued which are in ISO8601 format in UTC, and then you are creating Date objects from them.
This part of your code is fine:
if (element.createdDate) element.createdDate = new Date(element.createdDate.toString());
You parse the string, and the resulting Date object is correct.
However, you don't need to use .toString() here, as the value is already a string. That is redundant.
This part of your code is the problem:
console.log("javascript date: " + new Date(element.depositDate.getUTCDate().toString()));
The getUTCDate function returns just the date of the month. Don't use that.
No matter what you do to create the Date object, ultimately you create a Date object and you're relying upon an implicit string conversion to output it. This will have different behavior in different browsers.
Consider console.log(new Date()):
In Chrome, this logs something like Fri Mar 17 2017 12:14:29 GMT-0700 (Pacific Daylight Time) on my computer. This is as if I called console.log(new Date().toString()); It is in an RFC 2822 like format (but not quite), and is represented in local time.
In Firefox, this logs something like 2017-03-17T19:14:46.535Z. This is as if I called console.log(new Date().toISOString()); It is in ISO8601 format, and is represented in UTC.
The point is, don't rely on implicit undefined behavior. If you must work with Date objects, then you should use console.log(element.createdDate.toISOString()) to see the ISO8601 representation of the UTC time.
If you're going to be doing a lot of things with dates and times, you may prefer to use a library, such as Moment.js, which can make tasks such as this more clear.
I have dates stored in my database in UTC format and calling
element.createdDate = new Date(element.createdDate.toString());
results in displaying the wrong date.
2016-10-11T00:00:00Z and Mon Oct 10 2016 20:00:00 GMT-04:00 (EDT) are exactly the same moment in time. The only difference is that one is displayed in ISO 8601 extended format with timezone offset 00:00 and the other is displayed in an RFC 2822 (like) format with timezone offset -04:00 (and assumes a locality in the EDT region).
calling
element.createdDate = new Date(element.createdDate.toUTCString());
returns nothing.
That is unusual. Typically it would return either a string or an error, but without a working example or any code to provide context it's impossible to say why.
How do I go about displaying the correct time from UTC?
You haven't specified what "correct" is. You are displaying a date and time for the same moment in time, just in a different format and time zone.

How to parse date string from database without time shift?

I am getting 2016-07-13T00:00:00.000Z string from database and converting it to MM/DD/YYYY format with moment.js like this:
result = moment('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
which prints 07/12/2016 but I was expecting 07/13/2016.
Local Linux timezone is America/New_York. date command prints this Mon Jul 4 04:28:19 EDT 2016
The date that you have is in UTC, as signified by the z at the end.
When you use the default moment constructor, moment(), it converts the time you pass it from the specified offset (in this case UTC) to the local time of the machine. This is why your date is changing. Because this is a UTC date, to keep it exactly the same you can use moment.utc():
moment.utc('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
Alternately, parseZone would work as well:
moment.parseZone('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
For more information about all of the constructor functions in moment, see the parsing guide
or this blog post
You should use momentjs timezone : http://momentjs.com/timezone/
yourdate = moment.tz("2016-07-13T00:00:00.000Z", "America/New_York");
alert(yourdate.format('MM/DD/YYYY'));
This should give you the correct date in output.

Json stringify changes dates

Hello I have an object in js with a field date. I try to stringify it at an ajax request but the result is inconsistent. After stringify the new object is one day earlier.
To be more specific this is the code on my file:
console.log(reservation.checkin);
console.log( JSON.stringify(reservation.checkin));
And this is the outcome:
Thu Jan 01 2015 00:00:00 GMT+0200 (EET)
"2014-12-31T22:00:00.000Z"
Am I doing something wrong? Is that output what it should be? Thx in advance!
edit: From an answer below it seems that it is at different timezone. What is the correct way to stringify this date?
It's not changing the date, just showing it in another timezone (UTC / GMT)
GMT+0200 (EET) means 2 hours differenece with UTC / GMT
so that's exaclty what you see in the result.
it depends a bit on the purpose. If you want ot post this in another API, it should work fine (presuming, the api uses timezone standards), in case you want to just show it in a gui... why use the json stringify...
I am not going to do all the math for you, i suggest you know why now, so just google: 'javascript format timezone' or something like that.
e.g:
Convert date to another timezone in JavaScript
Well, it is timezone - your date is GMT +2:00,
and after applying Stringify you get UTC.
You may want to check Date method .getTimezoneOffset() and maybe update the date
JSON.stringify is calling Date.toJSON() to convert the date.
See The "right" JSON date format.

Categories

Resources