Enable/disable Daylight Savings Time through command line on Ubuntu 18.04 - datetime

Note: By "Disable" daylight savings time, I mean for the system clock to ignore any time changes for daylight savings time (ie, if DST is disabled, then the clock will not "spring forward" an hour in March and will not "fall back" an hour in November.
I am designing an Qt application to run on Ubuntu 18.04 and I need to be able to set system timezone, time and date.
For settings time and date, I can easily use timedatctl to modify the system settings. However, this command does seem to be able to disable Daylight Savings Time. It does report whether DST is "Active" or not depending on the timezone and date, but you cannot disable/enable this settings.
On Windows, I had used tzutil.exe to setting DST enabled or not using the dst_off flag. Is there are any equivalent to Ubuntu?

I'll answer this question from a time zone perspective.
Disabling DST is generally not a good thing. Such features ignore the reality of time zones. Time zones are defined by individual governments around the world, and those same governments dictate where and when DST is in effect.
As an example, I'm located in Redmond, Washington, USA. By US law this is located in the Pacific Time zone, which is UTC-8 during standard time and UTC-7 during daylight time. US law currently allows states to opt-out of DST, which Arizona and Hawaii have done. But Washington has not, and thus DST is applicable for me here. Right now (in July) it is 11:00 PDT as I'm writing this. I cannot just decide for myself that its 10:00 PST. I would have to relocate to a different time zone to do that.
The time zones in the IANA time zone database (TZDB, Olson, etc.) which are used in most systems, including Ubuntu, define distinct areas around the world where local time has agreed since at least 1970. If there are areas that share the same standard time but differ in whether they get DST or not, or when DST applies, then they get their own distinct entry in the TZDB. In other words, there is no purpose in saying "I want to be in America/Los_Angeles without DST" because there is no place in the Pacific time zone that does that. If you're in the Pitcairn islands (UTC-8 without DST), then you simply use Pacific/Pitcairn.
Maybe a clearer example: Most of US Mountain Time uses MST (UTC-7) and MDT (UTC-6), which gets the TZDB identifier America/Denver. Arizona, most of which does not use daylight saving time, uses MST (UTC-7) all year, so it gets its own identifier of America/Phoenix in the TZDB.
Then you may ask, well why does Windows have a "Disable DST" feature? There are a few reasons I can talk publicly about (disclosure: I work at Microsoft, occasionally in this area).
The Windows time zone feature was originally created with Windows NT. At that time, the Olson database was around but was not as ubiquitous as it is today. Microsoft decided to create their own implementation, and thus to this day there are two different sources of time zones data. TZDB and Microsoft.
It used to be the case that the Windows time zone data did not cover the whole world. Thus, some Windows users had to rely on this feature to get accurate time. This changed dramatically with an update in June 2016 to align with Microsoft's mission statement of "... every person and every organization on the planet ...". Today, there is commitment and policy to ensuring accurate time zone data.
When a government decides to make changes to their time zone (enacting DST, suspending DST, changing DST dates or times, changing a standard time offset, etc.), occasionally the lawmakers make a crucial mistake of not providing enough lead time (see my blog post on this subject). When that happens, Microsoft may offer suggested temporary guidance on how to get the correct local time until an update can be provided. Such guidance may include disabling DST or switching to a different time zone. These recommendations are always temporary, thus it becomes debatable whether the feature needs to exist at all.
In general, most Windows users should never disable DST. If they find themselves needing to do that to get local time correct (outside of the rare case described above), they're probably just not setting their time zone to the correct entry in the first place.
TZDB time zones on Ubuntu and other OSs tend to have shorter update cycles than Windows, and thus are not impacted as heavily by short-notice changes.

Related

How to convert 'YYYY-MM-DD hh:mm:ss.mmmmmm' (timezone CET (Amsterdam) and with DST) to 'CICS ABSTIME'?

I have a requirement to fill a PIC S9(15) COMP-3 variable with an CICS ABSTIME. (I believe this is the number of milliseconds that passed since the beginning op the year 1900)
My input is in the format YYYY-MM-DD hh:mm:ss.mmmmmm.
This represents an timestamp in the CET timezone (Amsterdam) and follows the daylight saving time ('DST').
I've found part of the solution:
EXEC CICS CONVERTTIME
DATESTRING ('Tuesday, 09-Oct-07 04:57:43 GMT')
ABSTIME (WS-TIMESTAMP)
END-EXEC
Results in the ABSTIME +003400898263000
But CONVERTTIME can only handle 4 date format types (RFC 1123, RFC 3339, RFC 850, ASCtime) none of which that can handle both the timezone and automatically the DST
See:
https://www.ibm.com/support/knowledgecenter/SSGMCP_5.4.0/reference/commands-api/dfhp4_converttime.html
Which is the proper Cobol (/CICS) way of converting a date, including timezone and DST to ABSTIME?
I agree with Hogstrom that summer/winter (daylight/standard) time shifts have changed and are subject to future change, so fundamentally this is a data-driven problem to solve and re-solve. If you care about leap seconds, that's a similar problem. If you care about fairly recent historical time, the Netherlands had these interesting timezone offsets (standard time here):
May 1, 1909, to July 1, 1937: UTC+0h19m32.13s (yes, seriously)
July 1, 1937, to May 16, 1940: UTC+0h20m
The Netherlands observed DST from 1916 to 1945, stopped observing it from 1946 to 1976, then started observing it again from 1977. And it's possible the Netherlands didn't start/end DST consistently according to the same date rules in the years when DST applied. (I'm not sure about that part.) There's active debate in the European Union right now about harmonizing time zones and possibly getting rid of summer/winter time shifts, so it's reasonable to plan ahead, to try to avoid embedding Y2K-like problems into this solution. Whatever you do, you want to try to make your code reasonably future proof.
OK, with that background, and if the supplier of this time-related data insists on providing local Amsterdam time rather than helping you out with UTC, I think you ought to have some sort of input file, parameter list, or table that defines how to convert from Amsterdam local time to UTC. You may wish to throw an error if/when presented with dates/times earlier than January 1, 1977. If your application supports tracing or logging of some kind, I'd write out information about when the local to UTC time conversion ruleset was last updated. I'd also put some sort of date code comment/versioning information in the file/table/rule set. Programmatically apply the rules defined in that input file first, then pass the UTC into the code you have above. If you want to get a bit fancy (in a good way) you could define the time zone/DST rules in a BRMS such as IBM Operational Decision Manager (ODM) for z/OS if you have that (which may already have such rules), then call the BRMS from COBOL.
Another possibility is to make the conversion from local time zone/DST to UTC using java.time. This article explains how that's done:
https://www.baeldung.com/java-daylight-savings
Naturally you can run Java programs in CICS (very well indeed), and Java Standard Edition is part of the base z/OS operating system, included and supported at no additional charge. (Liberty Profile is also part of CICS Transaction Server, although this is so simple you don't need Liberty.)
The peril here is that if the Java distributor (IBM in this case) or, more likely, the system operator doesn't keep the Java runtime current, and then your program could apply an obsolete conversion rule from local to UTC whenever somebody decides to change the rules in the future. So I reluctantly prefer an input rule file/table/parameter list-based approach of some kind.
OK, what input file/table/parameter list? Well, IANA's Timezone Database would be a really good choice:
https://data.iana.org/time-zones/tz-link.html
Your code would only likely need to handle a small subset of this database, but as the "source of truth" it's quite a good one.

What is the difference between UTC and GMT?

I have a few queries regarding the Time zones:
Can the time be captured in UTC alone?
Is UTC -6 and GMT -6 the same, and does that mean it is US local time?
Say, I have UTC time as "02-01-2018 00:03" does that mean my US local time is "01-01-2018 18:00"?
I have searched on Wikipedia and many related websites but haven't found a relevant explanation.
Astronomy versus Atomic clock
By the original definitions the difference is that GMT (also officially known as Universal Time (UT), which may be confusing) is based on astronomical observations while UTC is based on atomic clocks. Later GMT has become to be used at least unofficially to refer to UTC, which blurs the distinction somewhat.
GMT stands for Greenwich Mean Time, the mean solar time at the Royal Observatory in Greenwich on the south bank in Eastern London, UK. When the sun is at its highest point exactly above Greenwich, it is 12 noon GMT. Except: The Earth spins slightly unevenly, so 12 noon is defined as the annual average, mean of when the sun is at its highest, its culmination. In GMT there can never be any leap seconds because Earth’s rotation doesn’t leap.
UTC, which stands for Coordinated Universal Time in English, is defined by atomic clocks, but is otherwise the same. In UTC a second always has the same length. Leap seconds are inserted in UTC to keep UTC and GMT from drifting apart. By contrast, in GMT the seconds are stretched as necessary, so in principle they don’t always have the same length.
For roughly 100 years GMT was used as the basis for defining time around the world. Since the world these days mostly bases precise definition of time on atomic clocks, it has become customary to base the definition of time on UTC instead.
Edit: The original meaning of GMT is somewhat useless these days, but the three letter combination doesn’t seem to go away. I take it that it is often used without regard to whether UTC is really intended, so don’t put too much trust into the strict definition given above.
For your questions:
Yes, time can be captured in UTC alone. Storing time in UTC and using UTC for transmitting date-time information is generally considered good practice.
I suppose it’s up to each state of the US to define its time. And I don’t know, but I suppose that today they (officially or in practice) define time as an offset from UTC rather than GMT. The difference between the two will always be less than a second, so for many purposes you will not need to care. Central Standard Time (for example America/Chicago) is at offset -6, as is Mountain Daylight Time (for example America/Denver). On the other hand, offset -6 doesn’t necessarily imply a time in the US. Parts of Canada and Mexico use it too, of course, and also Galapagos and Easter Island.
I don’t think you got your example time exactly right, but yes, 2 January 2018 at 00:00 UTC is the same point in time as 1 January 2018 at 18:00 in Chicago and other places that are at UTC-6 in winter (winter on the Northern hemisphere, that is).
Further reading:
Systems of Time.
Current Millis with a simple and a complex take on UTC vs. GMT.
❌ The accepted Answer is neither correct nor useful.
✅ In contrast, the Answer by Ole V.V. correctly summarizes the technical differences — for details follow the links to detailed pages in Wikipedia.
For programmers building business-oriented apps, the upshot is that UTC is the new GMT. You can use the terms interchangeably, with the difference being literally less than a second. So for all practical purposes in most apps, no difference at all.
Here is some more practical advice, with code examples.
Strings
Say, I have UTC time as "02-01-2018 00:03" does that mean my US local time is "01-01-2018 18:00"?
That first part is a bad example, with the date-time string lacking an indicator of its offset or zone.
If a string indicates a specific moment, it must indicate either a time zone (Continent/Region formatted name) and/or an offset-from-UTC as a number of hours-minutes-seconds. If the string is meant to represent a moment at UTC itself, that means an offset-from-UTC of zero.
To write that string with an offset, various conventions may be applied. The best in practice is with both hours and minutes along with a colon, such as +00:00, +05:30, or -08:00. The leading zero and the colon are both optional but I have seen libraries break when encountering a value such as -0800 or -8.
Zulu
As a shortcut for an offset of zero, the letter Z is commonly used to mean UTC itself. Pronounced Zulu.
ISO 8601
Furthermore, best practice in formatting date-time textually for computing is to us the ISO 8601 standard formats. For a date-time the format YYYY-MM-DDTHH:MM:SS±HH:MM:SS is used. The T separates the date portion from the time-of-day portion. This format has advantages such as being largely unambiguous, easy to parse by machine, easy to read by humans across cultures. Another advantage is sorting alphabetically is also chronological. The standard accepts the Z abbreviation as well.
So your example UTC time as "02-01-2018 00:03" is better stated as 2018-01-02T00:03Z.
java.time
Be very aware that most programming languages, libraries, and databases have very poor support for date-time handling, usually based on a poor understanding of date-time issues. Handling date-time is surprisingly complicated and tricky to master.
The only decent library I have encountered is the java.time classes (see Tutorial) bundled with Java 8 and later, and its predecessor the Joda-Time project (also loosely ported from Java to .Net in the Noda Time project).
In java.time, a moment is represent in three ways. All have a resolution of nanoseconds.
InstantAlways in UTC. Technically, a count of nanoseconds since the epoch reference of first moment of 1970 (1970-01-01T00:00:00Z).
OffsetDateTimeA date with time-of-day in the context of a certain number of hours-minutes-seconds ahead of, or behind, UTC.
ZonedDateTimeA date with time-of-day in the context of a certain time zone.
So what is the difference between a time zone and an offset-from-UTC? Why do we need separate classes? An offset-from-UTC is simply a number of hours-minutes-seconds, three numbers, no more, no less. A time zone in much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region.
What changes? Changes dictated by the whims or wisdom of their politicians. Politicians around the world have shown a predilection for changing the offset used by the time zone(s) in their jurisdiction. Daylight Saving Time (DST) is one common pattern of changes, with its schedule often changed and the decision to enact or revert from DST sometimes changed. Other changes happen too, such as just in the last few years North Korea changing their clock by half-an-hour to sync with South Korea, Venezuela turning back their clock half-an-hour only to jump back forward less than a decade later, Turkey this year canceled the scheduled change from DST to standard time with little forewarning, and contemporary Russia having made multiple such changes in recent years.
Back to your example in your point # 3, let's look at some code.
Say, I have UTC time as "02-01-2018 00:03" does that mean my US local time is "01-01-2018 18:00"?
Your example strings have another problem. That 03 minute in the first part is ignored your second part, an apparent typo. I know because there is no time zone adjustment in effect in the Americas on that date involving a fractional hour of 57 minutes.
Not a moment
First, we parse your input string. Lacking any indicator of zone or offset, we must parse using the LocalDateTime. The name LocalDateTime may be misleading, as it does mean a specific locality. It means any or all localities. For more explanation, see What's the difference between Instant and LocalDateTime?.
String input = "2018-01-02T00:03" ; // Text of a date with time-of-day but without any context of time zore or offset-from-UTC. *Not* a moment, *not* a point on the timeline.
LocalDateTime ldt = LocalDateTime.parse( input ) ; // Parsing the input as a `LocalDateTime`, a class representing a date with time but no zone/offset. Again, this does *not* represent a moment, is *not* a point on the timeline.
UTC
By the facts given in the Question, we know this date and time was intended to represent a moment in UTC. So we can assign the context of an offset-from-UTC of zero hours-minutes-seconds for UTC itself. We apply a ZoneOffset constant UTC to get a OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ); // We are certain this text was intended to represent a moment in UTC. So correct the faulty text input by assigning the context of an offset of zero, for UTC itself.
Time zone
The Question asks to see this moment through a wall-clock time of six hours behind UTC used in the United States. One time zone with such an offset is America/Chicago.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as CST, EST, or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Chicago" ) ; // Adjust from UTC to a time zone where the wall-clock time is six hours behind UTC.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See this code run live at IdeOne.com.
odt.toString(): 2018-01-02T00:03Z
zdt.toString(): 2018-01-01T18:03-06:00[America/Chicago]
Same moment, different wall-clock time
This odt and zdt both represent the same simultaneous moment, the same point on the timeline. The only difference is the wall-clock time.
Let's work an example, using Iceland where their time zone uses an offset-from-UTC of zero hours-minutes-seconds. So the zone Atlantic/Reykjavik has a wall-clock time identical to UTC. At least currently today their wall-clock time matches UTC; in the past or future it may be different, which is why it is incorrect to say “UTC is the time zone of Iceland”. Anyway, our example… say someone in Reykjavík, Iceland with 3 minutes after midnight on the clock hanging on their wall makes a phone call to someone in the US. That US person lives in a place using the Chicago region time zone. As the person called picks up their phone, they glance up at the clock hanging on their wall to see the time is just after 6 PM (18:03). Same moment, different wall-clock time.
Also, the calendars hanging on their walls are different, as it is “tomorrow” in Iceland but “yesterday” in mainland US. Same moment, different dates!
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
There is no time difference between Coordinated Universal Time and Greenwich Mean Time.
7:17 AM Friday, Coordinated Universal Time (UTC) is
7:17 AM Friday, Greenwich Mean Time (GMT)
Key difference: Both UTC and GMT are time standards that differ in terms of their derivation and their use.
To quote timeanddate.com:
The Difference Between GMT and UTC:
Greenwich Mean Time (GMT) is often interchanged or confused with
Coordinated Universal Time (UTC). But GMT is a time zone and UTC is a
time standard.
Although GMT and UTC share the same current time in practice, there is
a basic difference between the two:
GMT is a time zone officially used in some European and African countries. The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm).
UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or
territory officially uses UTC as a local time.
GMT is a mean solar time calculated at the Greenwich meridian. https://www.rmg.co.uk/discover/explore/greenwich-mean-time-gmt
UTC is based on the extremely regular "ticking" of caesium atomic clocks. https://en.wikipedia.org/wiki/Coordinated_Universal_Time
They are neither based on the same time nor calculated the same way. IMHO, the wording on https://currentmillis.com is misleading, at best, if not just flat out incorrect.

iCAL DTSTART and DTEND format confusion. Should be easy to answer

I'm writing an iCAL file. I work on a cruise ship and the file will basically be my itinerary for the next 6 months, which I want to share with other crew members, to be displayed on our phones (a mixture of iPhones and Android phones). I want to included the name of the port we visit, and the arrival and departure times. So far, so easy.
BUT, on a cruise ship we pass through different time zones on an almost daily basis. Some people use local carrier info to set their phone timezones, others adjust the timezone manually, and some don't bother doing either. I tried this once before, but got very confused with TIMEZONE formats: whether to use UTC with a 'Z' prefix, whether to specify the country codes, etc.
HOWEVER, a recent bit of googling turned up the 'floating' DTSTART and DTEND format, aka 'Local Time', which seems to do away with all the region and timezone specifications. So, am I right in thinking the following will work?
(Source data: 23 Nov, Rio De Janeiro, 8:00am to 6:00pm,
and 25 Nov, A Different Port, 10:00am to 8:30pm)
BEGIN:VCALENDAR
VERSION:2.0
PRODID: MyNameHere
BEGIN:VEVENT
UID:milesmuso.mf#qwertyqwertyqwerty.com
DTSTAMP:20171123T080000Z
DTSTART:20171123T080000
DTEND:20171123T180000
SUMMARY:Rio De Janiero
END:VEVENT
.
BEGIN:VEVENT
UID:milesmuso.mf#qwertyqwertyqwerty.com
DTSTAMP:20171125T100000Z
DTSTART:20171125T100000
DTEND:20171125T203000
SUMMARY:Another Port
END:VEVENT
.
.
BEGIN: VEVENT
(next event here)
END VEVENT
END:VCALENDAR
And if that syntax IS correct, then do I still need to specify DTSTAMP:20171123T080000Z with the 'Z' suffix? (something I read on https://www.kanzaki.com/docs/ical/dtstamp.html said that the 'Z' suffix is mandatory, even though I don't WANT to use UTC - I just want floating start and end times.)
Also, should the DTSTAMP time be the same as the DTSTART time for each event, or do I use the same one for each event?
I hope you can help
Thanks
Miles,
Musician,
Celebrity Infinity
Using floating time means that the timezone that's actually used, is actually in the timezone of the viewer of the event.
So if you schedule something at 8PM floating time, and: "User A" has their timezone set to Eastern, and it's 7:55pm, the event will occur 5 minutes from now, then user "B" who has their phone set to Central time will see that the event starts one hour + 5 minutes from now.
In other words, using floating time means that the actual time as viewed by the user is going to depend on the viewer of the event.
This is not what you want. Because you are going to arriving and departing at fixed points in time. You really have two options:
Use UTC.
Use local time + a timezone of the port
UTC might be simpler in your case, but there's a caveat. You mention Rio De Janairo, and Brazil's treatment of DST (daylight savings time) has not been stellar.
So it's possible that you plan to arrive your ship at 2PM localtime somewhere, but a few weeks before you do, the Brazilian government decides to postpone or scrap daylight savings time that year. The question is then, does the boat depart an hour later (still 2PM local time) or does it depart at the exact same time from a UTC perspective?
You might consider this an edge case and make adjustments if needed, when they do but I thought it was worth talking about this scenario.
Anyway, ignoring that, both "local time + TZ" or "UTC" will probably be good enough for you. If you use "America/Sao_Paulo" for a departure time, and people:
Automatically got a time and timezone from a carrier, it will "just work"
Manually changed their timezone, it will "just work"
I think I would prefer the local time + TZ because it's the most 'accurate' representation of the event.

Daylight saving time and time zone best practices [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am hoping to make this question and the answers to it the definitive guide to dealing with daylight saving time, in particular for dealing with the actual change overs.
If you have anything to add, please do
Many systems are dependent on keeping accurate time, the problem is with changes to time due to daylight savings - moving the clock forward or backwards.
For instance, one has business rules in an order taking system that depend on the time of the order - if the clock changes, the rules might not be as clear. How should the time of the order be persisted? There are of course an endless number of scenarios - this one is simply an illustrative one.
How have you dealt with the daylight saving issue?
What assumptions are part of your solution? (looking for context here)
As important, if not more so:
What did you try that did not work?
Why did it not work?
I would be interested in programming, OS, data persistence and other pertinent aspects of the issue.
General answers are great, but I would also like to see details especially if they are only available on one platform.
Summary of answers and other data: (please add yours)
Do:
Whenever you are referring to an exact moment in time, persist the time according to a unified standard that is not affected by daylight savings. (GMT and UTC are equivalent with this regard, but it is preferred to use the term UTC. Notice that UTC is also known as Zulu or Z time.)
If instead you choose to persist a (past) time using a local time value, include the local time offset for this particular time from UTC (this offset may change throughout the year), such that the timestamp can later be interpreted unambiguously.
In some cases, you may need to store both the UTC time and the equivalent local time. Often this is done with two separate fields, but some platforms support a datetimeoffset type that can store both in a single field.
When storing timestamps as a numeric value, use Unix time - which is the number of whole seconds since 1970-01-01T00:00:00Z (excluding leap seconds). If you require higher precision, use milliseconds instead. This value should always be based on UTC, without any time zone adjustment.
If you might later need to modify the timestamp, include the original time zone ID so you can determine if the offset may have changed from the original value recorded.
When scheduling future events, usually local time is preferred instead of UTC, as it is common for the offset to change. See answer, and blog post.
When storing whole dates, such as birthdays and anniversaries, do not convert to UTC or any other time zone.
When possible, store in a date-only data type that does not include a time of day.
If such a type is not available, be sure to always ignore the time-of-day when interpreting the value. If you cannot be assured that the time-of-day will be ignored, choose 12:00 Noon, rather than 00:00 Midnight as a more safe representative time on that day.
Remember that time zone offsets are not always an integer number of hours (for example, Indian Standard Time is UTC+05:30, and Nepal uses UTC+05:45).
If using Java, use java.time for Java 8 and later.
Much of that java.time functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport library.
Further adapted for early Android (< 26) in the ThreeTenABP library.
These projects officially supplant the venerable Joda-Time, now in maintenance-mode. Joda-Time, ThreeTen-Backport, ThreeTen-Extra, java.time classes, and JSR 310 are led by the same man, Stephen Colebourne.
If using .NET, consider using Noda Time.
If using .NET without Noda Time, consider that DateTimeOffset is often a better choice than DateTime.
If using Perl, use DateTime.
If using Python 3.9 or later, use the built-in zoneinfo for working with time zones. Otherwise, use dateutil or arrow. The older pytz library can generally be avoided.
If using JavaScript, avoid using the older moment.js or moment-timezone libraries, as they are no longer actively maintained. See the Moment.js project status for more details. Instead, consider Luxon, date-fns, day.js, or js-joda.
If using PHP > 5.2, use the native time zones conversions provided by DateTime, and DateTimeZone classes. Be careful when using DateTimeZone::listAbbreviations() - see answer. To keep PHP with up to date Olson data, install periodically the timezonedb PECL package; see answer.
If using C++, be sure to use a library that uses the properly implements the IANA timezone database. These include cctz, ICU, and Howard Hinnant's "tz" library. In C++20 the latter is adopted into the standard <chrono> library.
Do not use Boost for time zone conversions. While its API claims to support standard IANA (aka "zoneinfo") identifiers, it crudely maps them to POSIX-style data, without considering the rich history of changes each zone may have had. (Also, the file has fallen out of maintenance.)
If using Rust, use chrono.
Most business rules use civil time, rather than UTC or GMT. Therefore, plan to convert UTC timestamps to a local time zone before applying application logic.
Remember that time zones and offsets are not fixed and may change. For instance, historically US and UK used the same dates to 'spring forward' and 'fall back'. However, in 2007 the US changed the dates that the clocks get changed on. This now means that for 48 weeks of the year the difference between London time and New York time is 5 hours and for 4 weeks (3 in the spring, 1 in the autumn) it is 4 hours. Be aware of items like this in any calculations that involve multiple zones.
Consider the type of time (actual event time, broadcast time, relative time, historical time, recurring time) what elements (timestamp, time zone offset and time zone name) you need to store for correct retrieval - see "Types of Time" in this answer.
Keep your OS, database and application tzdata files in sync, between themselves and the rest of the world.
On servers, set hardware clocks and OS clocks to UTC rather than a local time zone.
Regardless of the previous bullet point, server-side code, including web sites, should never expect the local time zone of the server to be anything in particular. see answer.
Prefer working with time zones on a case-by-case basis in your application code, rather than globally through config file settings or defaults.
Use NTP services on all servers.
If using FAT32, remember that timestamps are stored in local time, not UTC.
When dealing with recurring events (weekly TV show, for example), remember that the time changes with DST and will be different across time zones.
Always query date-time values as lower-bound inclusive, upper-bound exclusive (>=, <).
Don't:
Do not confuse a "time zone", such as America/New_York with a "time zone offset", such as -05:00. They are two different things. See the timezone tag wiki.
Do not use JavaScript's Date object to perform date and time calculations in older web browsers, as ECMAScript 5.1 and lower has a design flaw that may use daylight saving time incorrectly. (This was fixed in ECMAScript 6 / 2015).
Never trust the client's clock. It may very well be incorrect.
Don't tell people to "always use UTC everywhere". This widespread advice is shortsighted of several valid scenarios that are described earlier in this document. Instead, use the appropriate time reference for the data you are working with. (Timestamping can use UTC, but future time scheduling and date-only values should not.)
Testing:
When testing, make sure you test countries in the Western, Eastern, Northern and Southern hemispheres (in fact in each quarter of the globe, so 4 regions), with both DST in progress and not (gives 8), and a country that does not use DST (another 4 to cover all regions, making 12 in total).
Test transition of DST, i.e. when you are currently in summer time, select a time value from winter.
Test boundary cases, such as a timezone that is UTC+12, with DST, making the local time UTC+13 in summer and even places that are UTC+13 in winter
Test all third-party libraries and applications and make sure they handle time zone data correctly.
Test half-hour time zones, at least.
Reference:
The detailed timezone tag wiki page on Stack Overflow
Olson database, aka Tz_database
IETF draft procedures for maintaining the Olson database
Sources for Time Zone and DST
ISO format (ISO 8601)
Mapping between Olson database and Windows Time Zone Ids, from the Unicode Consortium
Time Zone page on Wikipedia
StackOverflow questions tagged dst
StackOverflow questions tagged timezone
Dealing with DST - Microsoft DateTime best practices
Network Time Protocol on Wikipedia
Other:
Lobby your representative to end the abomination that is DST. We can always hope...
Lobby for Earth Standard Time
I'm not sure what I can add to the answers above, but here are a few points from me:
Types of times
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
Relative time: eg: This question has an open bounty closing in 21 hours. This is easy to display
Recurring time: eg: A TV show is on every Monday at 9pm, even when DST changes.
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 times
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.
Offsets and names
An example of the above would be:
The soccer world cup finals game
happened in South Africa (UTC+2--SAST)
on July 11, 2010 at 19:00 UTC.
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.
System Time
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.
Clients
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.
Trivia
Finally, governments will sometimes do very weird things:
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.
Ok, I think I'm done.
This is an important and surprisingly tough issue. The truth is that there is no completely satisfying standard for persisting time. For example, the SQL standard and the ISO format (ISO 8601) are clearly not enough.
From the conceptual point of view, one usually deals with two types of time-date data, and it's convenient to distinguish them (the above standards do not) : "physical time" and "civil time".
A "physical" instant of time is a point in the continuous universal timeline that physics deal with (ignoring relativity, of course). This concept can be adequately coded-persisted in UTC, for example (if you can ignore leap seconds).
A "civil" time is a datetime specification that follows civil norms: a point of time here is fully specified by a set of datetime fields (Y,M,D,H,MM,S,FS) plus a TZ (timezone specification) (also a "calendar", actually; but lets assume we restrict the discussion to Gregorian calendar). A timezone and a calendar jointly allow (in principle) to map from one representation to another. But civil and physical time instants are fundamentally different types of magnitudes, and they should be kept conceptually separated and treated differently (an analogy: arrays of bytes and character strings).
The issue is confusing because we speak of these types events interchangeably, and because the civil times are subject to political changes. The problem (and the need to distinguish these concepts) becomes more evident for events in the future. Example (taken from my discussion here.
John records in his calendar a reminder for some event at datetime
2019-Jul-27, 10:30:00, TZ=Chile/Santiago, (which has offset GMT-4,
hence it corresponds to UTC 2019-Jul-27 14:30:00). But some day
in the future, the country decides to change the TZ offset to GMT-5.
Now, when the day comes... should that reminder trigger at
A) 2019-Jul-27 10:30:00 Chile/Santiago = UTC time 2019-Jul-27 15:30:00 ?
or
B) 2019-Jul-27 9:30:00 Chile/Santiago = UTC time 2019-Jul-27 14:30:00 ?
There is no correct answer, unless one knows what John conceptually meant
when he told the calendar "Please ring me at 2019-Jul-27, 10:30:00
TZ=Chile/Santiago".
Did he mean a "civil date-time" ("when the clocks in my city tell
10:30")? In that case, A) is the correct answer.
Or did he mean a "physical instant of time", a point in the continuus
line of time of our universe, say, "when the next solar eclipse
happens". In that case, answer B) is the correct one.
A few Date/Time APIs get this distinction right: among them, Jodatime, which is the foundation of the next (third!) Java DateTime API (JSR 310).
Make clear architectural separation of concerns - to know exactly which tier interacts with users, and has to change date-time for/from canonical representation (UTC). Non-UTC date-time is presentation (follows users local timezone), UTC time is model (remains unique for back-end and mid tiers).
Also, decide what's your actual audience, what you don't have to serve and where do you draw the line. Don't touch exotic calendars unless you actually have important customers there and then consider separate user-facing server(s) just for that region.
If you can acquire and maintain user's location, use location for systematic date-time conversion (say .NET culture or a SQL table) but provide a way for end-user to choose overrides if date-time is critical for your users.
If there are historical audit obligations involved (like telling exactly when Jo in AZ paid a bill 2 yrs ago in September) then keep both UTC and local time for the record (your conversion tables will change in a course of time).
Define the time referential time zone for data that comes in bulk - like files, web services etc. Say East Coast company has data center in CA - you need to ask and know what they use as a standard instead of assuming one or the other.
Don't trust time-zone offsets embedded in textual representation of the date-time and don't accept to parse and follow them. Instead always request that time zone and/or reference zone have to be explicitly defined. You can easily receive time with PST offset but the time is actually EST since that's the client's reference time and records were just exported at a server which is in PST.
You need to know about the Olson tz database, which is available from ftp://elsie.nci.nih.gov/pub http://iana.org/time-zones/. It is updated multiple times per year to deal with the often last-minute changes in when (and whether) to switch between winter and summer (standard and daylight saving) time in different countries around the world. In 2009, the last release was 2009s; in 2010, it was 2010n; in 2011, it was 2011n; at the end of May 2012, the release was 2012c. Note that there is a set of code to manage the data and the actual time zone data itself, in two separate archives (tzcode20xxy.tar.gz and tzdata20xxy.tar.gz). Both code and data are in the public domain.
This is the source of time zone names such as America/Los_Angeles (and synonyms such as US/Pacific).
If you need to keep track of different zones, then you need the Olson database. As others have advised, you also want to store the data in a fixed format — UTC is normally the one chosen — along with a record of the time zone in which the data was generated. You may want to distinguish between the offset from UTC at the time and the time zone name; that can make a difference later. Also, knowing that it is currently 2010-03-28T23:47:00-07:00 (US/Pacific) may or may not help you with interpreting the value 2010-11-15T12:30 — which is presumably specified in PST (Pacific Standard Time) rather than PDT (Pacific Daylight Saving Time).
The standard C library interfaces are not dreadfully helpful with this sort of stuff.
The Olson data has moved, in part because A D Olson will be retiring soon, and in part because there was a (now dismissed) law suit against the maintainers for copyright infringement. The time zone database is now managed under the auspices of IANA, the Internet Assigned Numbers Authority, and there's a link on the front page to 'Time Zone Database'. The discussion mailing list is now tz#iana.org; the announcement list is tz-announce#iana.org.
In general, include the local time offset (including DST offset) in stored timestamps: UTC alone is not enough if you later want to display the timestamp in its original timezone (and DST setting).
Keep in mind that the offset is not always an integer number of hours (e.g. Indian Standard Time is UTC+05:30).
For example, suitable formats are a tuple (unix time, offset in minutes) or ISO 8601.
Crossing the boundary of "computer time" and "people time" is a nightmare. The main one being that there is no sort of standard for the rules governing timezones and daylight saving times. Countries are free to change their timezone and DST rules at any time, and they do.
Some countries e.g. Israel, Brazil, decide each year when to have their daylight saving times, so it is impossible to know in advance when (if) DST will be in effect. Others have fixed(ish) rules as to when DST is in effect. Other countries do not use DST as all.
Timezones do not have to be full hour differences from GMT. Nepal is +5.45. There are even timezones that are +13. That means that:
SUN 23:00 in Howland Island (-12)
MON 11:00 GMT
TUE 00:00 in Tonga (+13)
are all the same time, yet 3 different days!
There is also no clear standard on the abbreviations for timezones, and how they change when in DST so you end up with things like this:
AST Arab Standard Time UTC+03
AST Arabian Standard Time UTC+04
AST Arabic Standard Time UTC+03
The best advice is to stay away from local times as much as possible and stick to UTC where you can. Only convert to local times at the last possible moment.
When testing make sure you test countries in the Western and Eastern hemispheres, with both DST in progress and not and a country that does not use DST (6 in total).
For PHP:
The DateTimeZone class in PHP > 5.2 is already based on the Olson DB which others mention, so if you are doing timezone conversions in PHP and not in the DB, you are exempt of working with (the hard-to-understand) Olson files.
However, PHP is not updated as frequently as the Olson DB, so just using PHPs time zone conversions may leave you with outdated DST information and influence the correctness of your data. While this is not expected to happen frequently, it may happen, and will happen if you have a large base of users worldwide.
To cope with the above issue, use the timezonedb pecl package. Its function is to update PHP's timezone data. Install this package as frequently as it is updated. (I'm not sure if the updates to this package follow Olson updates exactly, but it seems to be updated at a frequency which is at least very close to the frequency of Olson updates.)
If your design can accommodate it, avoid local time conversion all together!
I know to some this might sound insane but think about UX: users process near, relative dates (today, yesterday, next Monday) faster than absolute dates (2010.09.17, Friday Sept 17) on glance. And when you think about it more, the accuracy of timezones (and DST) is more important the closer the date is to now(), so if you can express dates/datetimes in a relative format for +/- 1 or 2 weeks, the rest of the dates can be UTC and it wont matter too much to 95% of users.
This way you can store all dates in UTC and do the relative comparisons in UTC and simply show the user UTC dates outside of your Relative Date Threshold.
This can also apply to user input too (but generally in a more limited fashion). Selecting from a drop down that only has { Yesterday, Today, Tomorrow, Next Monday, Next Thursday } is so much simpler and easier for the user than a date picker. Date pickers are some of the most pain inducing components of form filling. Of course this will not work for all cases but you can see that it only takes a little clever design to make it very powerful.
I recently had a problem in a web application where on an Ajax post-back the datetime coming back to my server-side code was different from the datetime served out.
It most likely had to do with my JavaScript code on the client that built up the date for posting back to the client as string, because JavaScript was adjusting for time zone and daylight savings, and in some browsers the calculation for when to apply daylight savings seemed to be different than in others.
In the end I opted to remove date and time calculations on the client entirely, and posted back to my server on an integer key which then got translated to date time on the server, to allow for consistent transformations.
My learning from this:
Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
While I haven't tried it, an approach to time zone adjustments I would find compelling would be as follows:
Store everything in UTC.
Create a table TZOffsets with three columns: RegionClassId, StartDateTime, and OffsetMinutes (int, in minutes).
In the table, store a list of dates and times when the local time changed, and by how much. The number of regions in the table and the number of dates would depend on what range of dates and areas of the world you need to support. Think of this as if it is "historical" date, even though the dates should include the future to some practical limit.
When you need to compute the local time of any UTC time, just do this:
SELECT DATEADD('m', SUM(OffsetMinutes), #inputdatetime) AS LocalDateTime
FROM TZOffsets
WHERE StartDateTime <= #inputdatetime
AND RegionClassId = #RegionClassId;
You might want to cache this table in your app and use LINQ or some similar means to do the queries rather than hitting the database.
This data can be distilled from the public domain tz database.
Advantages and footnotes of this approach:
No rules are baked into code, you can adjust the offsets for new regions or date ranges readily.
You don't have to support every range of dates or regions, you can add them as needed.
Regions don't have to correspond directly to geopolitical boundaries, and to avoid duplication of rows (for instance, most states in the US handle DST the same way), you can have broad RegionClass entries that link in another table to more traditional lists of states, countries, etc.
For situations like the US where the start and end date of DST has changed over the past few years, this is pretty easy to deal with.
Since the StartDateTime field can store a time as well, the 2:00 AM standard change-over time is handled easily.
Not everywhere in the world uses a 1-hour DST. This handles those cases easily.
The data table is cross-platform and could be a separate open-source project that could be used by developers who use nearly any database platform or programming language.
This can be used for offsets that have nothing to do with time zones. For instance, the 1-second adjustments that happen from time to time to adjust for the Earth's rotation, historical adjustments to and within the Gregorian calendar, etc.
Since this is in a database table, standard report queries, etc. can take advantage of the data without a trip through business logic code.
This handles time zone offsets as well if you want it to, and can even account for special historical cases where a region is assigned to another time zone. All you need is an initial date that assigns a time zone offset to each region with a minimal start date. This would require creating at least one region for each time zone, but would allow you to ask interesting questions like: "What is the difference in local time between Yuma, Arizona and Seattle, Washington on February 2, 1989 at 5:00am?" (Just subtract one SUM() from the other).
Now, the only disadvantage of this approach or any other is that conversions from local time to GMT are not perfect, since any DST change that has a negative offset to the clock repeats a given local time. No easy way to deal with that one, I'm afraid, which is one reason storing local times is bad news in the first place.
I have hit this on two types of systems, “shift planning systems (e.g. factory workers)” and “gas depend management systems)…
23 and 25 hour long days are a pain to cope with, so are 8hr shifts that take 7hr or 9hr. The problem is you will find that each customers, or even department of the customer have different rules they have created (often without documenting) on what they do in these special cases.
Some questions are best not asked of the customer’s until after they have paid for your “off the shelf” software. It is very rare to find a customer that thinks about this type of issue up front when buying software.
I think in all cases you should record time in UTC and convert to/from local time before storing the date/time. However even know which take a given time is in can be hard with Daylight saving and time zones.
For the web, the rules aren't that complicated...
Server-side, use UTC
Client-side, use Olson
Reason: UTC-offsets are not daylight savings-safe (e.g. New York is EST (UTC - 5 Hours) part of the year, EDT (UTC - 4 Hours) rest of the year).
For client-side time zone determination, you have two options:
1) Have user set zone (Safer)
Resources: Web-ready Olson tz HTML Dropdown and JSON
2) Auto-detect zone
Resource: jsTimezoneDetect
The rest is just UTC/local conversion using your server-side datetime libraries. Good to go...
When it comes to applications that run on a server, including web sites and other back-end services, the time zone setting of the server should be ignored by the application.
The common advice is to set the server's time zone to UTC. This is indeed a good best practice, but it's there as a band-aid for applications that do not follow other best practices. For example, a service might be writing to log files with local timestamps instead of UTC-based timestamps, thus creating ambiguities during the daylight saving time fall-back transition. Setting the server's time zone to UTC will fix that application. However the real fix would be for the application to log using UTC to begin with.
Server-side code, including web sites, should never expect the local time zone of the server to be anything in particular.
In some languages, the local time zone can easily creep in to application code. For example, the DateTime.ToUniversalTime method in .NET will convert from the local time zone to UTC, and the DateTime.Now property returns the current time in the local time zone. Also, the Date constructor in JavaScript uses the computer's local time zone. There are many other examples like this. It is important to practice defensive programming, avoiding any code that uses the computer's local time zone setting.
Reserve using the local time zone for client-side code, such as desktop applications, mobile applications, and client-side JavaScript.
Keep your servers set to UTC, and make sure they all are configured for ntp or the equivalent.
UTC avoids daylight savings time issues, and out-of-sync servers can cause unpredictable results that take a while to diagnose.
Be careful when dealing with timestamps stored in the FAT32 filesystem - it is always persisted in local time coordinates (which include DST - see msdn article). Got burned on that one.
One other thing, make sure the servers have the up to date daylight savings patch applied.
We had a situation last year where our times were consistently out by one hour for a three-week period for North American users, even though we were using a UTC based system.
It turns out in the end it was the servers. They just needed an up-to-date patch applied (Windows Server 2003).
PHP's DateTimeZone::listAbbreviations() output
This PHP method returns an associative array containing some 'major' timezones (like CEST), which on their own contain more specific 'geographic' timezones (like Europe/Amsterdam).
If you're using these timezones and their offset/DST information, it's extremely important to realize the following:
It seems like all different offset/DST configurations (including historical configurations) of each timezone are included!
For example, Europe/Amsterdam can be found six times in the output of this function. Two occurrences (offset 1172/4772) are for the Amsterdam time used until 1937; two (1200/4800) are for the time that was used between 1937 and 1940; and two (3600/4800) are for the time used since 1940.
Therefore, you cannot rely on the offset/DST information returned by this function as being currently correct/in use!
If you want to know the current offset/DST of a certain timezone, you'll have to do something like this:
<?php
$now = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo $now->getOffset();
?>
If you happen to maintain database systems that are running with DST active, check carefully whether they need to be shut down during the transition in fall. Mandy DBS (or other systems as well) don't like passing the same point in (local) time twice, which is exactly what happens when you turn back the clock in fall. SAP has solved this with a (IMHO really neat) workaround - instead of turning back the clock, they just let the internal clock run at half the usual speed for two hours...
Are you using the .NET framework?
If so, let me introduce you to the DateTimeOffset type, added with .NET 3.5.
This structure holds both a DateTime and an Offset (TimeSpan), which specifies the difference between the DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).
The DateTimeOffset.Now static method will return a DateTimeOffset
instance consisting of the current (local) time, and the local offset
(as defined in the operating system's regional info).
The DateTimeOffset.UtcNow static method will return a
DateTimeOffset instance consisting of the current time in UTC (as
if you were in Greenwich).
Other helpful types are the TimeZone and TimeZoneInfo classes.
For those struggling with this on .NET, see if using DateTimeOffset and/or TimeZoneInfo are worth your while.
If you want to use IANA/Olson time zones, or find the built in types are insufficient for your needs, check out Noda Time, which offers a much smarter date and time API for .NET.
Business rules should always work on civil time (unless there's legislation that says otherwise). Be aware that civil time is a mess, but it's what people use so it's what is important.
Internally, keep timestamps in something like civil-time-seconds-from-epoch. The epoch doesn't matter particularly (I favour the Unix epoch) but it does make things easier than the alternative. Pretend that leap-seconds don't exist unless you're doing something that really needs them (e.g., satellite tracking). The mapping between timestamps and displayed time is the only point where DST rules should be applied; the rules change frequently (on a global level, several times a year; blame politicians) so you should make sure that you do not hard-code the mapping. Olson's TZ database is invaluable.
Just one example to prove that handling time is the huge mess described, and that you can never be complacent. In several spots on this page leap-seconds have been ignored.
Several years ago, the Android operating system used GPS satellites to get a UTC time reference, but ignored the fact that GPS satellites do not use leap-seconds. No one noticed until there was confusion on New Year's Eve, when the Apple phone users and Android phone users did their count-downs about 15 seconds apart.
I think it has since been fixed, but you never know when these 'minor details' will come back to haunt you.
Just wanted to point out two things that seem inaccurate or at least confusing:
Always persist time according to a unified standard that is not
affected by daylight savings. GMT and UTC have been mentioned by
different people, though UTC seems to be mentioned most often.
For (almost) all practical computing purposes, UTC is, in fact, GMT. Unless you see a timestamps with a fractional second, you're dealing with GMT which makes this distinction redundant.
Include the local time offset as is (including DST offset) when
storing timestamps.
A timestamp is always represented in GMT and thus has no offset.
Here is my experience:-
(Does not require any third-party library)
On server-side, store times in UTC format so that all date/time values in database are in a single standard regardless of location of users, servers, timezones or DST.
On the UI layer or in emails sent out to user, you need to show times according to user. For that matter, you need to have user's timezone offset so that you can add this offset to your database's UTC value which will result in user's local time. You can either take user's timezone offset when they are signing up or you can auto-detect them in web and mobile platforms. For websites, JavaScript's function getTimezoneOffset() method is a standard since version 1.0 and compatible with all browsers. (Ref: http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp)
Tom Scott's video about timezones on YouTube on the Computerphile channel has also a nice and entertaining description of the topic.
Examples include:
Samoa (an island in the Pacific Ocean) shifting its time zone forward by 24 hours to make trading easier with Australia and New Zealand,
West Bank, where 2 populations of people are following different time zones,
18th century changes from the Julian calendar to the Gregorian
calendar (which happened in the 20th century in Russia).
Actually, kernel32.dll does not export SystemTimeToTzSpecificLocation. It does however export the following two: SystemTimeToTzSpecificLocalTime and TzSpecificLocalTimeToSystemTime...
Never rely only on constructors like
new DateTime(int year, int month, int day, int hour, int minute, TimeZone timezone)
They can throw exceptions when a certain date time does not exist due to DST. Instead, build your own methods for creating such dates. In them, catch any exceptions that occur due to DST, and adjust the time is needed with the transition offset. DST may occur on different dates and at different hours (even at midnight for Brazil) according to the timezone.
Never, ever store local time without its UTC offset (or a reference to the time zone)—examples of how not to do it include FAT32 and struct tm in C.¹
Understand that a time zone is a combination of
a set of UTC offsets (e.g. +0100 in winter, +0200 in summer)
rules for when the switchover happens (which may change over time: for example, in the 1990s the EU harmonized the switchover as being on the last Sundays in March and October, at 02:00 standard time/03:00 DST; previously this differed between member states).
¹ Some implementations of struct tm do store the UTC offset, but this has not made it into the standard.
In dealing with databases (in particular MySQL, but this applies to most databases), I found it hard to store UTC.
Databases usually work with server datetime by default (that is, CURRENT_TIMESTAMP).
You may not be able to change the server timezone.
Even if you are able to change the timezone, you may have third-party code that expects server timezone to be local.
I found it easier to just store server datetime in the database, then let the database convert the stored datetime back to UTC (that is, UNIX_TIMESTAMP()) in the SQL statements. After that you can use the datetime as UTC in your code.
If you have 100% control over the server and all code, it's probably better to change server timezone to UTC.

How do computers figure out date information?

Most languages have some sort of date function where you really don't have to do any programming to get any date information you just get it from the date function/object. I am curious what goes on behind the scenes to make this happen?
Every computer has a system clock which keeps track of date and time. On the lowest level, date and time information it retrieved from there. Above that add timezone information, etc. from the operating system and you got a Date object or something similar.
Depending on your language/environment Date objects can either perform date calculation themselves or you have to use other functions to achieve that. Those ensure that leap years get handled correctly and no invalid date can be created.
But maybe I got your question wrong.
Typically a computer is storing a count of how many of a certain unit of time has gone by since a specific time and date in the past. In Unix systems, for example, this could be the number of seconds since the Unix Epoch, which is midnight, Jan 1st 1970 GMT. In Windows, this is the number of 100 ns intervals since 1601-01-0 (thanks Johannes Rössel). Or it could be something as simple as number of seconds since the computer was powered on.
So from the number of units that have gone by since that time/date, an OS can calculate the number of years, months, days, etc that have gone by. Of course all sorts of fun stuff like leap years and leap seconds have to be taken into account for this to occur.
Systems such as NTP (Network Time Protocol) can be used to synchronize a computer's internal count to atomic clocks via an NTP server over a network. To do this, they NTP takes into account the round trip time and learns the sorts of errors the link to the NTP server.
Date and time information is provided usually by operating system, so it's a system call. Operating system deals with realtime clock mounted on computer mainboard and powered by small battery (which lasts for years).
Well ... Most computers contain a "real-time clock", which counts time on the human scale of seconds, minutes etc. Traditionally, there is a small battery on the motherboard, that lets the chip either remember the time, or even keep counting it, even when the rest of the computer is powered off.
Many computers today use services like the network time protocol to periodically query a centralized high-precision clock, to set the current time. In this way, even if the battery is removed (or just fails), the computer will still know what time and date it is, and be able to update (to correct for errors in the real-time chip's time-keeping) that information as often as necessary.
Aside from the realtime clock, date calculations are mostly a software library function.
Dates are rather irregular and so behind the scenes a mixture of approximations, corrections and lookup-tables are used.
The representation of a date can vary as well, usually some (arbitrary) startdate is used. A common system, also used by astronomers are the Julian day numbers (not to be confused with the Julian calendar). Dates can be stored as seconds-since-start or as days-since-start (the latter is usually a floating point). Here are some more algorithms.
A surprising amount of surprisingly complicated code is required for date parsing, computation, creation etc.
For example, in Java, dates are computed, modified, stored etc via the Date, Calendar, and specifically and typically, the Gregorian Calendar implementation of Calendar. (You can download the SDK/JDK and look at the source for yourself.)
In short, what I took from a quick perusal of the source is: Date handling is non-trivial and not something you want to attempt on your own. Find a good library if at all possible, else you will almost certainly be reinventing the square wheel.
Your computer has a system clock and the BIOS has a timer function that can be updated from your OS. Languages only take the information from there and some can update it too.
Buy any of these books on Calendrical Calculations. They'll fill you in on how the date libraries work under the hood.
The date/time is often stored in terms of times since a certain date. For example ticks (100 nanosecond intervals) since January 1, 0001. It is also usueally stored in reference to UTC. The underlying methods in the OS, database, framework, application, etc. can then convert these to a more usable representation. Back in the day, systems would store component parts of the date, day, month, year, etc as a part of the data structure, but we learned our lesson with the Y2K mess that this probably isn't the best approach.
Most replies have been to do with how the current date is obtained. i.e. from system clock and so on.
If you want to know how it is stored and used there are many different implementations and it depends on the system.
I believe a common one is the use of a 64 bit signed integer in T-sql the 01/01/1970 is 0 so negative numbers are pre 1970 and positive on from that each increment adding 100 th of a second (think it's a 100th would need to check).
Why 01/01/1970 you may ask this is because the gregorian calendar is on a 400 year cycle. 01/01/1970 being the closes start of a cycle to the current date.
This is because "Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year." Makes it very complicated I believe the 400 year cycle coincides with the days of the week repeating as well but would nee dto check. Basically it's very complicated.
Internally it is incredibly difficult to write the datetime library accounting for all these variations such as leap years, the fact there is no year zero..... Not to mention UTC, GMT UT1 times.
We had occasion when debugging a client problem to look at how SQL stores datetimes... fairly interesting and makes pretty good sense once you see it.
SQL uses 2 4 byte integers...
The first 4 bytes are the date in days since Jan. 1st, 1753. I believe the maximum year is supposed to be 9999, which doesn't exactly line up to the number of available integers in 4 bytes, but there you go.
The second 4 bytes are the time in milliseconds since midnight.

Resources