Rectangle 27 4

IF you don't want the timezone offset to be included you can use Date.UTC

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

> new Date(2015,9,1)
  Date 2015-09-30T22:00:00.000Z  // reproduces your problem, my local time is GMT+0200
> new Date(Date.UTC(2015,9,1))
  Date 2015-10-01T00:00:00.000Z // UTC time

However 00:00:00 GMT+0200 and 22:00:00.000Z are just different ways to represent the timezone offset in Date's string representation. The difference is the method used when printing to console: most browsers use .toString() while Firefox uses .toISOString(). (Edited; previously stated that the toString method implementations are different which isn't true).

Thu Oct 01 2015 00:00:00 GMT+0200
Date 2015-09-30T22:00:00.000Z
.getDate()
.getMonth()
Date

It's not actually the Date.toString() implementation. That is fine. it's just that the debugger in FF uses Date.toISOString() instead.

javascript - new Date() shows differents results in Chrome or Firefox ...

javascript google-chrome date firefox
Rectangle 27 3

You can easily take care of the timezone offset by using the getTimezoneOffset() function in Javascript. For example,

var dt = new Date(1458619200000);
console.log(dt); // Gives Tue Mar 22 2016 09:30:00 GMT+0530 (IST)

dt.setTime(dt.getTime()+dt.getTimezoneOffset()*60*1000);
console.log(dt); // Gives Tue Mar 22 2016 04:00:00 GMT+0530 (IST)

var offset = -300; //Timezone offset for EST in minutes.
var estDate = new Date(dt.getTime() + offset*60*1000);
console.log(estDate); //Gives Mon Mar 21 2016 23:00:00 GMT+0530 (IST)

Though, the locale string represented at the back will not change. The source of this answer is in this post. Hope this helps!

is your unix time always in EST timezone? If so then you need to add the correct GMT offset for your input (-4 hours), then translate THAT to the local time zone by adding the local timezoneoffset() back into the unix time before creating a new date object.

what are you setting the time to, utc? how do I set it to a specific timezone

@foreyez From the UTC time, its easy to convert to any fixed timezone. You can simply add or subtract the timezone offset in the date object by using setTime(). For example, if your fixed timezone is UTC+10 (Australian Eastern Standard Time), +600*60*1000 will be the offset you can add to your time.

javascript - How to set date always to eastern time regardless of user...

javascript datetime timezone
Rectangle 27 92

Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.

To get a correct timezone in JavaScript, you should use

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Unfortunately, by the time of writing this, it's not yet widely supported. I know it's working correctly at least in Chrome.

ecma-402/1.0 says that timeZone may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.

In this version of the ECMAScript Internationalization API, the timeZone property will remain undefined if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor

in ecma-402/3.0 which is still in a draft it changed to

In this version of the ECMAScript 2015 Internationalization API, the timeZone property will be the name of the default time zone if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. The previous version left the timeZone property undefined in this case.

This is the only answer for getting the timezone, which some users may need as opposed to the offset only. So, as an update in 2016-09, Intl works on most modern browsers but not Safari. For that browser, there's a reasonably accurate javascript fallback here - pellepim.bitbucket.org/jstz

Verified that this now appears to work in Safari. (Using version 10.0)

Would be nice if this worked in all modern browsers. However IE11 and latest Firefox both return undefined for the timeZone property.

This should be marked as the answer - all overs get the offset, not the timezone.

I have tested in now with Chrome 58, Edge 40 and Firefox 53 - it works will all of them. It does not work with IE 11, I did not test Opera.

Getting the client's timezone in JavaScript - Stack Overflow

javascript timezone
Rectangle 27 10

You generally don't need to do much of "Timezone manipulation" on the client side. As a rule I try to store and work with UTC dates, in the form of ticks or "number of milliseconds since midnight of January 1, 1970." This really simplifies storage, sorting, calculation of offsets, and most of all, rids you of the headache of the "Daylight Saving Time" adjustments. Here's a little JavaScript code that I use.

To get the current UTC time:

function getCurrentTimeUTC()
{
    //RETURN:
    //      = number of milliseconds between current UTC time and midnight of January 1, 1970
    var tmLoc = new Date();
    //The offset is in minutes -- convert it to ms
    return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
}

Then what you'd generally need is to format date/time for the end-user for their local timezone and format. The following takes care of all the complexities of date and time formats on the client computer:

function formatDateTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date/time
    return new Date(nTicks).toLocaleString();
}

function formatDateFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date
    return new Date(nTicks).toLocaleDateString();
}

function formatTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted time
    return new Date(nTicks).toLocaleTimeString();
}

So the following example:

var ticks = getCurrentTimeUTC();  //Or get it from the server

var __s = "ticks=" + ticks + 
    ", DateTime=" + formatDateTimeFromTicks(ticks) +
    ", Date=" + formatDateFromTicks(ticks) +
    ", Time=" + formatTimeFromTicks(ticks);

document.write("<span>" + __s + "</span>");

Returns the following (for my U.S. English locale):

By adding the getTimezoneOffset value in your getCurrentTimeUTC function, you're actually returning a different point in time. The result of getTime is already in UTC.

@MattJohnson: That is incorrect. The result of tmLoc.getTime() is an offset against local time. That is easy to check if you have access to anything that runs JavaScript.

Sorry, but that's not true. See the MDN reference. You can also see this in the ECMAScript spec. 15.9.3.3 describes getTime, which points you at the "time value" defined in 15.9.5, which is a PrimitiveValue, as set in 15.9.3.3 explicitly as UTC.

Well, since you obtain tmLoc via new Date(), then its the same thing. The time zone will affect the string output of tmLoc.toString() and similar items, but it will not affect tmLoc.getTime() That's always just a number of milliseconds since midnight 1970-01-01 in UTC.

//The offset is in minutes -- convert it to ms

timezone - How do I get a UTC Timestamp in JavaScript? - Stack Overflo...

javascript timezone utc
Rectangle 27 10

You generally don't need to do much of "Timezone manipulation" on the client side. As a rule I try to store and work with UTC dates, in the form of ticks or "number of milliseconds since midnight of January 1, 1970." This really simplifies storage, sorting, calculation of offsets, and most of all, rids you of the headache of the "Daylight Saving Time" adjustments. Here's a little JavaScript code that I use.

To get the current UTC time:

function getCurrentTimeUTC()
{
    //RETURN:
    //      = number of milliseconds between current UTC time and midnight of January 1, 1970
    var tmLoc = new Date();
    //The offset is in minutes -- convert it to ms
    return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
}

Then what you'd generally need is to format date/time for the end-user for their local timezone and format. The following takes care of all the complexities of date and time formats on the client computer:

function formatDateTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date/time
    return new Date(nTicks).toLocaleString();
}

function formatDateFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date
    return new Date(nTicks).toLocaleDateString();
}

function formatTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted time
    return new Date(nTicks).toLocaleTimeString();
}

So the following example:

var ticks = getCurrentTimeUTC();  //Or get it from the server

var __s = "ticks=" + ticks + 
    ", DateTime=" + formatDateTimeFromTicks(ticks) +
    ", Date=" + formatDateFromTicks(ticks) +
    ", Time=" + formatTimeFromTicks(ticks);

document.write("<span>" + __s + "</span>");

Returns the following (for my U.S. English locale):

By adding the getTimezoneOffset value in your getCurrentTimeUTC function, you're actually returning a different point in time. The result of getTime is already in UTC.

@MattJohnson: That is incorrect. The result of tmLoc.getTime() is an offset against local time. That is easy to check if you have access to anything that runs JavaScript.

Sorry, but that's not true. See the MDN reference. You can also see this in the ECMAScript spec. 15.9.3.3 describes getTime, which points you at the "time value" defined in 15.9.5, which is a PrimitiveValue, as set in 15.9.3.3 explicitly as UTC.

Well, since you obtain tmLoc via new Date(), then its the same thing. The time zone will affect the string output of tmLoc.toString() and similar items, but it will not affect tmLoc.getTime() That's always just a number of milliseconds since midnight 1970-01-01 in UTC.

//The offset is in minutes -- convert it to ms

timezone - How do I get a UTC Timestamp in JavaScript? - Stack Overflo...

javascript timezone utc
Rectangle 27 46

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

On the same page, in the <head> section, first of all you need to include jQuery:

Also in the <head> section,, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://domain.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

</Westy92>

I think this solution is fundamentally wrong (at least in some situations), because it allows the user to change the time, to whatever he wants, by simply just calling domain.com/timezone.php

@VladasDirys This is information provided by the user's browser. Trying to secure it against the user is pointless.

php - get user timezone - Stack Overflow

php javascript timezone
Rectangle 27 277

Offsets and names

I'm not sure what I can add to the answers above, but here are a few points from me:

I'm not sure what I can add to the answers above, but here are a few points from me:

There are four different times you should consider:

There are four different times you should consider:

  • Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  • Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  • Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website
  • Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

  • Always store time in UTC
  • Always store time in UTC
  • Convert to local time on display (local being defined by the user looking at the data)
  • Convert to local time on display (local being defined by the user looking at the data)
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.

An example of the above would be:

An example of the above would be:

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Also, run ntpd on all boxes.

Also, run ntpd on all boxes.

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

This answer has some great points, I especially wanted to point this out part "Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes" Storing times in UTC in the DB and then converting for display helps handle a lot of the tricky aspects of dealing with time zones. However, handling "recurring events" that cross DST barriers becomes much tougher.

This answer has some great points, I especially wanted to point this out part "Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes" Storing times in UTC in the DB and then converting for display helps handle a lot of the tricky aspects of dealing with time zones. However, handling "recurring events" that cross DST barriers becomes much tougher.

+1 for the Trivia. Keeping the content interesting makes this task more enjoyable, which may lead to increased productivity :)

+1 for the Trivia. Keeping the content interesting makes this task more enjoyable, which may lead to increased productivity :)

A lot of good stuff in this answer, but a few issues. 1) Many time zone abbreviations are ambiguous. see here 2) Not always do you want to store in UTC. Most of the time - yes, but context matters. In your terms, television time would not be stored in UTC. Also, sometimes its unlawful or against policy to not store the local time - which is where things like DateTimeOffset (or equivalent) come in handy. Otherwise, good write up.

A lot of good stuff in this answer, but a few issues. 1) Many time zone abbreviations are ambiguous. see here 2) Not always do you want to store in UTC. Most of the time - yes, but context matters. In your terms, television time would not be stored in UTC. Also, sometimes its unlawful or against policy to not store the local time - which is where things like DateTimeOffset (or equivalent) come in handy. Otherwise, good write up.

The Netherlands trivia looks legit. ietf.org/rfc/rfc3339.txt section 5.8. Halfway figured someone was pulling our leg.

The Netherlands trivia looks legit. ietf.org/rfc/rfc3339.txt section 5.8. Halfway figured someone was pulling our leg.

datetime - Daylight saving time and time zone best practices - Stack O...

datetime timezone utc dst datetimeoffset
Rectangle 27 276

Offsets and names

I'm not sure what I can add to the answers above, but here are a few points from me:

There are four different times you should consider:

  • Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  • Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

  • Always store time in UTC
  • Convert to local time on display (local being defined by the user looking at the data)
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.

An example of the above would be:

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Also, run ntpd on all boxes.

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

This answer has some great points, I especially wanted to point this out part "Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes" Storing times in UTC in the DB and then converting for display helps handle a lot of the tricky aspects of dealing with time zones. However, handling "recurring events" that cross DST barriers becomes much tougher.

+1 for the Trivia. Keeping the content interesting makes this task more enjoyable, which may lead to increased productivity :)

A lot of good stuff in this answer, but a few issues. 1) Many time zone abbreviations are ambiguous. see here 2) Not always do you want to store in UTC. Most of the time - yes, but context matters. In your terms, television time would not be stored in UTC. Also, sometimes its unlawful or against policy to not store the local time - which is where things like DateTimeOffset (or equivalent) come in handy. Otherwise, good write up.

The Netherlands trivia looks legit. ietf.org/rfc/rfc3339.txt section 5.8. Halfway figured someone was pulling our leg.

datetime - Daylight saving time and time zone best practices - Stack O...

datetime timezone utc dst datetimeoffset
Rectangle 27 276

Offsets and names

I'm not sure what I can add to the answers above, but here are a few points from me:

There are four different times you should consider:

  • Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  • Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

  • Always store time in UTC
  • Convert to local time on display (local being defined by the user looking at the data)
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.

An example of the above would be:

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Also, run ntpd on all boxes.

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

This answer has some great points, I especially wanted to point this out part "Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes" Storing times in UTC in the DB and then converting for display helps handle a lot of the tricky aspects of dealing with time zones. However, handling "recurring events" that cross DST barriers becomes much tougher.

+1 for the Trivia. Keeping the content interesting makes this task more enjoyable, which may lead to increased productivity :)

A lot of good stuff in this answer, but a few issues. 1) Many time zone abbreviations are ambiguous. see here 2) Not always do you want to store in UTC. Most of the time - yes, but context matters. In your terms, television time would not be stored in UTC. Also, sometimes its unlawful or against policy to not store the local time - which is where things like DateTimeOffset (or equivalent) come in handy. Otherwise, good write up.

The Netherlands trivia looks legit. ietf.org/rfc/rfc3339.txt section 5.8. Halfway figured someone was pulling our leg.

datetime - Daylight saving time and time zone best practices - Stack O...

datetime timezone utc dst datetimeoffset
Rectangle 27 270

Offsets and names

I'm not sure what I can add to the answers above, but here are a few points from me:

There are four different times you should consider:

  • Event time: eg, the time when an international sporting event happens, or a coronation/death/etc. This is dependent on the timezone of the event and not of the viewer.
  • Television time: eg, a particular TV show is broadcast at 9pm local time all around the world. Important when thinking about publishing the results (of say American Idol) on your website

There is also Historic/alternate time. These are annoying because they may not map back to standard time. Eg: Julian dates, dates according to a Lunar calendar on Saturn, The Klingon calendar.

Storing start/end timestamps in UTC works well. For 1, you need an event timezone name + offset stored along with the event. For 2, you need a local time identifier stored with each region and a local timezone name + offset stored for every viewer (it's possible to derive this from the IP if you're in a crunch). For 3, store in UTC seconds and no need for timezones. 4 is a special case of 1 or 2 depending on whether it's a global or a local event, but you also need to store a created at timestamp so you can tell if a timezone definition changed before or after this event was created. This is necessary if you need to show historic data.

  • Always store time in UTC
  • Convert to local time on display (local being defined by the user looking at the data)
  • When storing a timezone, you need the name, timestamp and the offset. This is required because governments sometimes change the meanings of their timezones (eg: the US govt changed DST dates), and your application needs to handle things gracefully... eg: The exact timestamp when episodes of LOST showed both before and after DST rules changed.

An example of the above would be:

With this information, we can historically determine the exact time when the 2010 WCS finals took place even if the South African timezone definition changes, and be able to display that to viewers in their local timezone at the time when they query the database.

You also need to keep your OS, database and application tzdata files in sync, both with each other, and with the rest of the world, and test extensively when you upgrade. It's not unheard of that a third party app that you depend on did not handle a TZ change correctly.

Make sure hardware clocks are set to UTC, and if you're running servers around the world, make sure their OSes are configured to use UTC as well. This becomes apparent when you need to copy hourly rotated apache log files from servers in multiple timezones. Sorting them by filename only works if all files are named with the same timezone. It also means that you don't have to do date math in your head when you ssh from one box to another and need to compare timestamps.

Also, run ntpd on all boxes.

Never trust the timestamp you get from a client machine as valid. For example, the Date: HTTP headers, or a javascript Date.getTime() call. These are fine when used as opaque identifiers, or when doing date math during a single session on the same client, but don't try to cross-reference these values with something you have on the server. Your clients don't run NTP, and may not necessarily have a working battery for their BIOS clock.

Standard time in the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law from 1909-05-01 through 1937-06-30. This time zone cannot be represented exactly using the HH:MM format.

This answer has some great points, I especially wanted to point this out part "Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes" Storing times in UTC in the DB and then converting for display helps handle a lot of the tricky aspects of dealing with time zones. However, handling "recurring events" that cross DST barriers becomes much tougher.

+1 for the Trivia. Keeping the content interesting makes this task more enjoyable, which may lead to increased productivity :)

A lot of good stuff in this answer, but a few issues. 1) Many time zone abbreviations are ambiguous. see here 2) Not always do you want to store in UTC. Most of the time - yes, but context matters. In your terms, television time would not be stored in UTC. Also, sometimes its unlawful or against policy to not store the local time - which is where things like DateTimeOffset (or equivalent) come in handy. Otherwise, good write up.

The Netherlands trivia looks legit. ietf.org/rfc/rfc3339.txt section 5.8. Halfway figured someone was pulling our leg.

datetime - Daylight saving time and time zone best practices - Stack O...

datetime timezone utc dst datetimeoffset
Rectangle 27 16

there is no "timezone" request header, or something like that, so, you can't with php

but with javascript you can get the timezone offset of the client, then you could make a xmlhttp request to send informations to php

@AdamSack major sites detects timezones by registered users' info, they have their own geoip database. in plus darius said that changing the time on its computer, the change is detected, so they definitely use javascript.

I agree with @AdamSack still +1 for the Javascript ;)

Timezone offset is not constant, it changes with DST, thus it can be ambiguous what timezone a client uses. A combination of IP, js timezone offset and js locale should give better results (you need a database which combines all these somehow).

php - How are major sites detecting timezone? - Stack Overflow

php javascript zend-framework timezone
Rectangle 27 13

Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};
$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

jquery - How do I format a Microsoft JSON date? - Stack Overflow

jquery asp.net ajax json
Rectangle 27 13

Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};
$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

jquery - How do I format a Microsoft JSON date? - Stack Overflow

jquery asp.net ajax json
Rectangle 27 13

Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};
$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

jquery - How do I format a Microsoft JSON date? - Stack Overflow

jquery asp.net ajax json
Rectangle 27 13

Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:

new MyInfo {
    CreationDate = r.CreationDate.ToString("o"),
};
$.getJSON(
    "MyRestService.svc/myinfo",
    function (data) {
        $.each(data.myinfos, function (r) {
            this.CreatedOn = new Date(this.CreationDate);
        });
        // Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
       alert(data.myinfos[0].CreationDate.toLocaleString());
    }
)

Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.

jquery - How do I format a Microsoft JSON date? - Stack Overflow

jquery asp.net ajax json
Rectangle 27 2

In JavaScript, you can either work with UTC, or with the local time on the machine (but without knowing its timezone; you can at most determine the offset to UTC).

Many people have failed trying to convert timezones in JS, but all these approaches are doomed to fail, because of DST, leap years/seconds, etc. There are so many pitfalls which make an implementation extremely complex.

Time conversion operations are best done on a backend.

You say that you store the date in a DB, so I assume you're transfering it to some backend anyway.

Let's assume your backend is some PHP application, and you would collect the pure date as simple string (e.g. 2014-09-08 15:12:00) from a datepicker, as well as the timezone.

In PHP, you would now do the following:

$timestamp = strtotime($_POST['date']);
$dateLocal = new \DateTime("@$timestamp", new \DateTimezone($_POST['timezone']));
$dateUtc = $dateLocal->setTimezone(new \DateTimezone('UTC'));

Now, $dateUtc contains the date as rock-solid DateTime object in UTC, which you can now further process.

By the way if you would want to show the converted timezone to the user before doing anything else, I would implement this as some sort of AJAX service. As mentioned before, trying to convert timezones in JavaScript itself is doomed to fail.

It's not necessarily doomed to fail. It's true of course that for any timezone that is neither to local one nor UTC you should use a date library, not the native Date object.

@Bergi: I'd love to know of a JS library which has a near-flawless implementation of time conversion. At this time, I wouldn't trust any of those I've seen in the past.

github.com/mde/timezone-js seems pretty mature. I admit that I haven't used any, though.

momentjs.com looks nice too, but I haven't looked into it deeply.

javascript - How do I properly store UTC date in database from user da...

javascript datetime timezone
Rectangle 27 6

You can specify a time zone offset on new Date(), for example:

new Date('Feb 28 2013 19:00:00 GMT-0500')

Since Date store UTC time ( i.e. getTime returns in UTC ), javascript will them convert the time into UTC, and when you call things like toString javascript will convert the UTC time into browser's local timezone and return the string in local timezone, i.e. If I'm using UTC+8:

> new Date('Feb 28 2013 19:00:00 GMT-0500').toString()
< "Fri Mar 01 2013 08:00:00 GMT+0800 (CST)"
getHours/Minute/Second
> new Date('Feb 28 2013 19:00:00 GMT-0500').getHours()
< 8

( This 8 means after the time is converted into my local time - UTC+8, the hours number is 8. )

Parsing any format other than ISO 8601 extended format is implementation dependant and should not be relied on. There is no standard for timezone abbreviations, e.g. "EST" might represent any one of 3 different zones.

The examples in this comment often do not work in internet explorer. As mentioned in the previous comment to this post, ISO 8601 is important. I confirmed by reading the ECMA-262 (Javascript 5th) edition language Specification.

How to initialize javascript date to a particular timezone - Stack Ove...

javascript timezone
Rectangle 27 2

The only real way you will be able to tell for sure is if you have the DST information (including any updates) available on a server you can ask. The user's PC does not need to even have the timezone information installed.

Then you need a "dynamic" script to get the DST status.

Possible methods: Reference a PHP/ASPX/JSP/CFM/ASP page that generates a javascript to set a variable that indicates if DST is active or not, or the current number of minutes offset.

Write the script in your (hopefully dynamic) page directly.

Use AJAX/REST/JSON to access a Date/Time service somewhere that can tell you the DST status or number of minutes offset from UTC for a timezone/location.

Minutes is preferable to hours because DST offsets are actually in minutes around the world, not hours.

Offset time for DST in one specific timezone using JavaScript - Stack ...

javascript timezone dst
Rectangle 27 2

The only real way you will be able to tell for sure is if you have the DST information (including any updates) available on a server you can ask. The user's PC does not need to even have the timezone information installed.

Then you need a "dynamic" script to get the DST status.

Possible methods: Reference a PHP/ASPX/JSP/CFM/ASP page that generates a javascript to set a variable that indicates if DST is active or not, or the current number of minutes offset.

Write the script in your (hopefully dynamic) page directly.

Use AJAX/REST/JSON to access a Date/Time service somewhere that can tell you the DST status or number of minutes offset from UTC for a timezone/location.

Minutes is preferable to hours because DST offsets are actually in minutes around the world, not hours.

Offset time for DST in one specific timezone using JavaScript - Stack ...

javascript timezone dst
Rectangle 27 3

Time Zone != Offset. See the timezone tag wiki. So just swapping it for another time zone that happens to be on UTC-8 is not a good idea. You will pick up all the DST rules for that zone, which don't necessarily apply.

Even Pacific/Pitcairn isn't purely UTC-8 if you deal with past dates. It moved from UTC-08:30 to UTC-08:00 in 1998 - you can see that here.

This is one of the reasons I'm not happy with ActiveSupport::TimeZone. They make it quite clear in their docs that it is limited:

Limit the set of zones provided by TZInfo to a meaningful subset of 146 zones.

This seems rather arbitrary. Who is it that determines what is "meaningful" and what isn't? If it wasn't meaningful, it wouldn't have been in the database to begin with!

You should look at using the tzinfo gem, which is what ActiveSupport based theirs on anyway. It has the full TZDB with all of its time zone data instead of a limited subset.

Regarding time zone detection, I'm not sure what JavaScript you are using to "detect" the time zone. You show calling some functions get_timezone and TimeZoneFlash.extractOffset that must be custom to your app or provided by external libraries. Please elaborate on exactly what you're using.

The only timezone detection library for JavaScript that I am aware of is jsTimeZoneDetect - which makes it quite clear that it just takes an educated guess. Unless you are depending on the new internationalization APIs in the very newest Chrome an Opera (which I don't think you are), then there's no guaranteed way to detect a time zone without user involvement. See also this answer.

We have a check box to not allow DST Timings on Windows machine. So in this case with UTC-08:00 as time zone and DST box unchecked we're getting a value Pacific/Pitcairn.

Yes, that is an awful reality. IMHO - that should never be unchecked. It would be better if the checkbox wasn't there. Whether DST applies or not is handled by the time zone, so there's no good reason to disable it. I'm sure that they left it there specifically for cases like Pitcairn, because there isn't a Windows time zone entry for them specifically.

Take the current offset from JavaScript using new Date().getTimezoneOffset(). (It's in minutes, and the sign is reversed, so you may need some simple math.) Compare it to the current offset for the selected time zone in your drop down. (You should be able to get that from your server-side code.)

It's a jquery detect time zone plugin.

Ah. Yes, that in turn uses the library I mentioned. It just wraps it up as a jQuery plugin.

Be sure you understand the limitations of jsTimeZoneDetect. It's just a guess, it's not perfect. Any app that needs to do anything reasonably complex should have a time zone setting that the user can change. You can guess a default value, but you should let them change it. If you're looking for a nice way to present a list of time zones, consider this map-based picker.

I already have a drop-down for this. I am working on building a alert box for users who are in a different time zone compared to their browser's timezone. Even Intl.DateTimeFormat().resolved.timeZone wouldn't help because most of my traffic is from IE and FF browsers

javascript - Rails Time Zone Mapping for browser detected Timezones - ...

javascript ruby-on-rails ruby timezone