Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop javascript Date function from changing timezone offset

So I have iso date time that need to be converted from a string to date object. How do I keep date from converting it to local browser timezone.

new Date('2013-07-18T17:00:00-05:00')
Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)

I want to get

Thu Jul 18 2013 17:00:00 GMT-0500 (XX)

like image 538
user2434674 Avatar asked Jul 19 '13 17:07

user2434674


4 Answers

While MomentJS is a great library, it may not provide a solution for every use case. For example, my server provides dates in UTC, and when the time portion of the date is not saved in the db (because it's irrelevant), the client receives a string that has a default time of all zeros - midnight - and ends with an offset of +0000. The browser then automatically adjusts for my local time zone and pulls the time back by a few hours, resulting in the previous day.

This is true with MomentJs as well.

One solution is to slice off the time portion of the string, and then use MomentJS as described in the other answers.

But what happens if MomentJS is not a viable option, i.e. I already have many places that use a JS Date and don't want to update so many lines of code? The question is how to stop the browser from converting dates based on local time zone in the first place. And the answer is, when the date is in ISO format, you cannot.

However, there is no rule that says the string you pass to JavaScript's Date constructor must be in ISO format. If you simply replace the - that separates the year, month, and day with a /, your browser will not perform any conversion.

In my case, I simply changed the format of the Dates server-side, and the problem was solved without having to update all the client-side JS dates with MomentJS.

Note that the MDN docs for JavaScript's Date class warn about unpredictable browser-behavior when parsing a string to create a Date instance.

like image 157
andreisrob Avatar answered Oct 06 '22 04:10

andreisrob


You cannot change this behavior of Javascript because it is the only simple way for Javascript to work. What happens is simply that Javascript looks at the time shift, computes the matching timestamp, and then asks the OS for the representation of this timestamp in the local time zone. What is key to understand here is that -05:00 is not an indication of time zone but simply a shift from UTC.

Time zones are complex beasts that are just arbitrary political decisions. The OS provides a service to display time in the local time zone, but not in other time zones. To do that you have to take in account things like DST that are pretty much a hell.

As always with time management, the only decent way to tackle this problem is to use a dedicated library. In Javascript, you'll find Moment.js and Moment.Timezone.js very helpful.

Example http://codepen.io/Xowap/pen/XKpKZb?editors=0010

document.write(moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format('LLL'));

As a bonus, you get a ton of formatting/parsing features from Moment.js.

Please also note that as long as you use the ISO 8601, your date can be pinpointed to a precise moment, and thus be displayed in any timezone of your liking. In other words, JS "converting" your date doesn't matter.

like image 28
Xowap Avatar answered Oct 06 '22 03:10

Xowap


You can use a library such as Moment.js to do this.

See the String + Format parsing.

http://momentjs.com/docs/#/parsing/string-format/

The following should parse your date you provided, but you may need to modify it for your needs.

var dateString = "2013-07-18T17:00:00-05:00";

var dateObject = moment(dateString, "YYYY-MM-DDTHH:mm:ssZ").toDate();

Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.

http://momentjs.com/docs/#/parsing/string/

like image 31
penguin Avatar answered Oct 06 '22 05:10

penguin


This is an old question that recently got linked in an answer to a newer question, but none of the existing answers seem to fully address the original question.

In many cases the easiest way to format and display a datetime string in the time zone that it is received, is not to convert the string to a Date object at all. Instead, just parse the datetime string and recombine the parts into the desired format. For example, if you can live without the day of the week in the output requested in the question, you could do something like the following to handle the requested input and output format (including the day of the week adds enough complexity that it might be worth using a library at that point). Of course, this approach requires modification based on the format of the datetime strings you are receiving on the client side.

const months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'};
const format = (datetime) => {
  const [date, time] = datetime.split('T');
  const [y, m, d] = date.match(/\d+/g);
  const [t, tz] = time.split(/(?=[+-])/);
  return `${months[Number(m)]} ${d} ${y} ${t} GMT${tz}`;
};

const dt = format('2013-07-18T17:00:00-05:00');
console.log(dt);
// Jul 18 2013 17:00:00 GMT-05:00

There are JavaScript and other library methods that will allow you to convert your datetime string to a Date instance and then display it in a specific time zone if you are consistently receiving datetime strings from one or a few specific time zones that are easily identified on the client side. Following are a couple of examples.

toLocaleString enables you to display a date in a specific time zone but the options parameters required to set the time zone are not supported across all browsers (as of the date of this answer). For example (note that parsing of date strings with the Date constructor is still discouraged, but most modern browsers will handle an ISO 8601 format string like the one below):

const dt = new Date('2013-07-18T17:00:00-05:00');
const ny = dt.toLocaleString('en-US', { timeZone: 'America/New_York' });
console.log(`Local: ${dt}`);
console.log(`New York: ${ny}`);

You could also use Moment.js with Moment Timezone to display a date in a specific time zone. For example:

const ny = moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format();
console.log(`New York: ${ny}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

It is important to note the following when working with datetime strings and time zones in JavaScript. The JavaScript Date constructor DOES NOT change the time zone offset. When you create a date from a string using ISO 8601 format as in the question example, Date does the following:

Creates a JavaScript Date instance that represents a single moment in time. Date objects use a Unix Time Stamp, an integer value that is the number of milliseconds since 1 January 1970 UTC.

In other words, JavaScript Date instances do not store (or change) time zone offsets. The reason you often see output from a JavaScript Date in your local time zone is that toString is the default method called when you log a Date instance to the console (or use various other approaches to output your date). In most browser implementations, this method relies on the browser's local time zone to convert the number of milliseconds since 1 January 1970 UTC into a string representation of the date.

like image 32
benvc Avatar answered Oct 06 '22 04:10

benvc