Movatterモバイル変換


[0]ホーム

URL:


W3C

Working with Time and Timezones

W3C Group Draft Note

More details about this document
This version:
https://www.w3.org/TR/2024/DNOTE-timezone-20241122/
Latest published version:
https://www.w3.org/TR/timezone/
Latest editor's draft:
https://w3c.github.io/timezone/
History:
https://www.w3.org/standards/history/timezone/
Commit history
Editor:
Addison Phillips (Invited Expert)
Feedback:
GitHub w3c/timezone (pull requests,new issue,open issues)
Contributors:
See the Contributors section.

Copyright © 2022-2024World Wide Web Consortium.W3C®liability,trademark andpermissive document license rules apply.


Abstract

This document contains guidelines and best practices for working with time and time zones in applications and document formats. Use cases are provided to help choose an approach that ensures that geographically distributed applications work well with date and time values. This document also aims to provide a basic understanding and vocabulary for talking about time and time handling in software, a source of confusion for many developers and content authors on the Web.

Status of This Document

This section describes the status of this document at the time of its publication. A list of currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

We welcome comments on this document, but to make it easier to track them, please raise separate issues for each comment, and point to the section you are commenting on using a URL.

This document was published by theInternationalization Working Group as a Group Draft Note using theNote track.

Group Draft Notes are not endorsed byW3C nor its Members.

This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

TheW3C Patent Policy does not carry any licensing requirements or commitments on this document.

This document is governed by the03 November 2023W3C Process Document.

1.Contributors

This document is based on several previous documents. The original Working Group Note (Working With Timezones) was by Martin Dürst, Mark Davis, Felix Sasaki, and Addison Phillips. Alater revision was written by Martin Dürst, Mark Davis, Felix Sasaki, Richard Ishida, and Addison Phillips. Sections3.2A Brief History of Timekeeping and3.3What is a Time Zone? were adapted from an article and later a Unicode conference presentation (Time Out of Joint) by Addison Phillips. Information on time zone scenarios is based on work by Norbert Lindenberg. Information about temporal serializations and use cases is based on work by CJ Butenhoff.

2.Introduction

One common requirement for applications is the need to deal with dates, times, or durations. Working with time-related data can be complex because values are related to calendars and timekeeping rules, which themselves can be somewhat arcane. One of these complexities in working with time-related data is the effect of time zone on the handling and presentation of the data.

This document contains guidelines and best practices for working with date and time values, including time zones, in applications and document formats. Use cases are provided to help choose an approach that ensures that geographically distributed applications work well with date and time values. This document also aims to provide a basic understanding and vocabulary for talking about time, a source of confusion for many developers and content authors on the Web.

Note

In this document [RFC2119] keywords have their usual meaning. Best practices and definitions are set off from the remainder of the text with special formatting.

Examples appear with a different background color and decoration like this.

Best practices appear with a different background color and decoration like this.

Definitions appear with a different background color and decoration like this.

Gaps or recommendations for future work appear with a different background color and decoration like this.

2.1Why You Should Read This

Working with date and time values, including the effect of time zones on the display and processing of these values, can be confusing. By understanding how date and time values work and how to manage these values in applications or specify them in standards, you can prevent many problems.

When working with date and time values, the time zone, thelocale, and your choices for encoding, handling, and processing date and time values can produce different and perhaps unexpected or unwanted results. Some examples of errors due to improper date/time handling might include the items listed below. Reading the best practices and guidelines in this document can help you create specifications, designs, or implementations that avoid errors when working with time values.

Example 1

The system time of your browser when this page was loaded was:Friday, November 22, 2024 at 4:01:27 PM. This has anincremental time value of1732291287397.

Your browser's time zone is:UTC.

If a friend in a different time zone views this page at the same instant you do, they might see a very different time—perhaps even on a different day:

ZoneDateTime
UTCFriday, November 22, 202416:01
Pacific/NoumeaSaturday, November 23, 202403:01
Australia/AdelaideSaturday, November 23, 202402:31
Asia/TokyoSaturday, November 23, 202401:01
Asia/ShanghaiSaturday, November 23, 202400:01
Africa/NairobiFriday, November 22, 202419:01
Europe/ParisFriday, November 22, 202417:01
America/New_YorkFriday, November 22, 202411:01
America/Buenos_AiresFriday, November 22, 202413:01
Pacific/TahitiFriday, November 22, 202406:01

3.Concepts

This section provides the basic concepts, terminology, and background for those unfamiliar with the origins, processing, and representation of date and time values in modern computer systems.

3.1Definitions

These definitions are useful in understanding date/time values.

Chronology orcalendar A timekeeping system used to organize dates and times.

Many different chronologies and calendars have been used or are in use today around the world. These different systems have varying rules for organizing and dividing time values.

ISO Chronology is based on the [ISO8601] standard, which is thede facto world calendar. This system uses aproleptic Gregorian calendar.

Aproleptic calendar is a calendar that applies modern rules to all times in the past, as if the calendar were observed at that time.

For example, the Gregorian calendar was created in 1582 CE, but not adopted universally, even by countries observing the Julian calendar. A proleptic Gregorian calendar (and thus, by extension, theISO Chronology) applies year numbers, leap years, and dating for dates in the past, even when that would be inappropriate historically.

Observed Time A moment in time based on an observed event or events. For example, "local noon", the shortest day or the year, or the first new moon.

Wall Time A date or time value as experienced by human beings, so called because the value might be what is shown on a paper calendar or analog clock mounted on the wall in a given location at a given moment.

Epoch A specific moment in time that serves as a reference point for a givenchronology. The most common epoch is the Unix Epoch, which is used by the most common computer timekeeping systems and measures incremental time values from midnight, January 1, 1970 in the UTC time zone, i.e. from1970-01-01T00:00:00.000Z

Era A grouping within acalendar used to number years. Most eras start with year "1" and count up to the start of the next era. There are some exceptions to this: the Gregorian calendar's era "BCE" counts backwards, with 1 BCE being the year just before 1 CE (1 AD).

Ghost time Awall time that can never exist because of time zone orcalendar rules. For example, the date2023-02-29 is a "ghost time" because 2023 is not a leap year in the Gregorian calendar. Similarly, in theAmerica/Los_Angeles time zone, thewall time2:34 a.m. on the date2024-03-10 is a "ghost time" because, due to daylight-savings time, the clock skips from1:59 a.m. directly to3:00 a.m..

Timeline In a given chronology, the fixed sequence of moments, measured against theepoch. A datetime value is said to beon the timeline if it is attached to a discrete moment in time. This is a hallmark of incremental time values.

Incremental Time A datetime value consisting of monotonically increasing integer units measured from a specific moment in time (which is called theepoch). For example, the moment1970-01-02T00:00:00.000Z in theISO Chronology might have an incremental time value (measured in milliseconds) of86400000, since there are 86,400 seconds in a day and 1000 ms in a second.

Field-based Time A datetime value that stores the time value in separate fields (era, year, month, day, hour, minute, second, millisecond, etc.)

Floating Time Any date or time value that is not fixed to a specific incremental time value or time zone. Also called alocal orplain date or time value.

Instant Anincremental time in the Unixepoch. An instant can be converted for display in anycalendar and/or time zone and any two instants can be ordered in time.

Universal Coordinated Time orUTC is the basis for modern timekeeping. Among other things, it provides a common baseline for converting between incremental and wall time. UTC is also known as GMT (Greenwich Mean Time). There are some subtle differences between the two, but none that the average person would notice. The time zone offset for UTC is0. UTC is often indicated in field-based formats usingZ.

Local Time Offset The different (positive or negative) of a given location fromUTC. This is usually expressed as an offset in hours and minutes, such as+10:00 or-09:30.

Daylight Savings Time Also calledsummer time ordaylight time and abbreviatedDST. The practice of advancing clocks to make better use of longer periods of daylight during the summer, so that darkness falls at a laterwall time. Rules around observation (or non-observation) of DST is one feature of a time zone.

3.2A Brief History of Timekeeping

Computer systems tell time differently than people do. So it is helpful to understand how time works within computers as well as in the real world in order to get a handle on how to get the results that you want. This description is necessarily simplified.

Timekeeping has its roots in observable celestial events, such as sunrise, sunset, the longest/shortest day of the year, the phases of the moon, or the position of the constellations. This is calledobserved time and underpins the various customary systems for measuring time.

Conventions have been established by various cultures to organize time into more convenient units. For example, days are broken up into arbitrary units such as hours, minutes, and seconds or grouped together to form weeks. Years are broken up into months. They are also numbered starting from significant events or organized intoeras. Each unique cultural system for organizing time forms acalendar orchronology.

Gradually, over time, most chronologies have weakened or sometimes removed some of the ties to the original observational basis for events. For example, the Gregorian calendar's months do not correspond to the lunar cycle. Other calendars retain stronger linkages to specific celestial events. For example, most Islamic calendars use actual solar or lunar observations to determine the start of specific periods or months.

Mechanical timekeeping allows for more precision and standardization in counting or measuring events. We refer to the dates and times experienced in a given location aswall time because the date or time can be read from a printed calendar or a clock mounted on the wall.

The advent of speed-of-light communication (such as the telegraph) and efficient means of travel (such as railroads) meant that timekeeping based on local observations (such as "local noon") became inconvenient: it is difficult to manage schedules when each locality keeps its own clock! Even relatively small travel distances produce measurable differences in observed time. As a result, synchronization of different regions that observe the same calendar andwall time became necessary, resulting in the advent of time zones.

Observed time has many disadvantages computationally. Observed events are not always predictable or convenient to use. The advent of mechanical timekeeping has allowed a different kind of time to flourish:incremental time based on a monotonic progression of fixed units. In some cases, incremental time is merely a prediction of when an event might be observed.

The modern standardized system of timekeeping in computer systems is generally based on a few core standards.Universal Coordinated Time (or "UTC"), adopted in 1972 CE, is used for global synchronization of clocks and to define local time zone variations. Many systems set computer clocks using the UNIX epoch (counting time from January 1, 1970 in UTC). Standards such as [ISO8601] or [RFC3339] provide serialization schemes for the interchange of date and time values and most programming languagues or data formats provide data structures for storing or exchanging date and time values. These types of systems are usually based on theISO Chronology (also known as theGregorian calendar), although they can be converted to other systems, such as the one of the Islamic calendars, the Ethiopic or Chinese solar-lunar calendars, and so forth.

3.3What is a Time Zone?

A time zone is a set of rules for determining the local observed time (wall time) as it relates toincremental time (as used in most computing systems) for a particular geographical region.

Before the adoption of time zones, local time was derived directly from observation. Clocks might be set, for example, based on an observed event such as local noon. Traveling fairly short distances across the Earth's surface results in changes in local observed time: you only have to travel about 28 kilometers (17 miles) at the equator (and less distance the further north or south of the equator you are) to alter the observed local noon by one minute.

Time zones were originated in several countries by railroad operators. Before time zones were instituted, it was difficult know when trains would arrive or depart because local wall time might vary significantly from one station to another. This also made it difficult to schedule traffic across the rail network.

Railroads solved this problem by adopting fixed regions in which the same local time was used throughout. These "time zones" were intended to be about one observed hour wide: the local time in the middle of the time zone was used throughout the region so that the most observational deviation most people would see was about half an hour (and, assuming the population is evenly distributed, most people experienced a smaller deviation). This is a value small enough that most people won't notice the difference between actual and observed time.

In the modern era, most countries have a single time zone, but a number of larger or more geographically distributed countries have more than one.

3.3.1Daylight Savings or Summer Time

The concept of "Daylight Saving Time" (DST) or "Summer Time" is used as a way of allowing people more sunlight hours in the evening. Not all regions observe summer time: usually those nearer the equator do not need it. Whether summer time is observed and how it is observed varies by jurisdiction.

As the name implies, areas that use some form of "summer time" do so in the summer season. That is, they change their UTC offset forward (usually by one hour) sometime in the spring and the reverse when the observation of summer time ends in the autumn. Since "spring" and "autumn" happen in opposite parts of the year in the northern and southern hemispheres, the starting and ending days are different for time zones in opposite hemispheres.

Observation (or non-observation) of summer time is controlled by national, regional, and sometimes local governments. Regions that otherwise share a UTC offset, even those with similar latitude (or shared borders) can have differing summer time start or stop rules. Sometimes local authorities will make one-time changes to accommodate a special event (such as when hosting the Olympics). Governments sometimes change whether summer time is observed as well as changing when summer time begins or ends.

3.3.2What defines a time zone?

While other schemes exist, many applications use theIANA Time Zone Database [BCP175] and its associated set of identifiers to define time zones.

Time zones are defined by these considerations:

Local Time Offset Time zones are used to compute the offset ofwall time fromUTC. The local time offset is the difference (positive or negative) between when a given time event is observed in UTC and local time. If all time zones used one-hour offsets, there would be 24 world-wide time zones, ranging between 12 hours before UTC to 11 hours following UTC. However, there are some that use half-hour or even quarter-hour offsets (or even some odd offsets). In addition, some time zones fall outside a single 24-hour span.

Observation of summer time Some times zones include rules for observing daylight-savings or summer time, while others do not. The observation of summer time is defined by a set of rules that include:

  • Summer time offset The amount of time added to (or subtracted from) thelocal time offset when summer time is being observed. Nowadays this is always one hour, but other values are theoretically possible (and have been used historically).
  • Starting date Usually described as a specific date on a specific calendar, such as the "first Sunday in April"
  • Starting time The time of day when the switch occurs, such as "2 AM"
  • Ending date Like the starting date, the date on which to switch back to "standard time"
  • Ending time The time of day when the switch occurs, such as "2 AM"

Adoption Dates Regions that currently have a specific local time offset and summer time behavior may have had different rules in the past (or plan to adopt new rules in the near future). Correct handling of past time values requires treating such regions as separate time zones.

Example 2

Adoption dates can be applied to any of the values that define a time zone, such as the amount of summer time offset and the starting/ending dates or times for summer time. For example, prior to 2007, the United States started daylight-savings time at 2 a.m. on the first Sunday in April for each time zone observing daylight-savings. In 2007, the USA changed the start date and time to 2 a.m. on the second Sunday in March.

Example 3

Korea Standard Time and Japan Standard Time currently use the same UTC offset and neither uses summer time. However, Japan abandoned summer time in 1951, while South Korea used it last in 1988, so an application that tracks time values that reach back that far might need to track these time zones separately.

3.3.3Time Zone Identifiers

The most definitive reference for identifying sets of time zone rules is the IANA Timezone Database [BCP175], which is used by systems such as various Linux distributions, Java, CLDR, ICU, and many other systems and libraries. Other systems exist: for example, Microsoft Windows uses its own data set and identifiers.

In the TZ database, time zones are given IDs that usually consist of a region and exemplar city. Regions can be continents (such as Europe or America) or oceans (such as Atlantic or Pacific). An exemplar city is a city in the time zone in question that should be well-known to people using the time zone. The TZ database also supplies aliases for many IDs; for example,Asia/Ulan Bator is equivalent toAsia/Ulaanbaatar. The Common Locale Data Repository [CLDR] can be used to provide a localized form for the IDs: see Appendix J in [UAX35]. Note: some systems, such as Apple Inc.'s MacOS, provide additional exemplar cities.

Example 4: Examples of time zone IDs
IDDescription
America/Los_AngelesUS Pacific time zone
Europe/LondonUK time; not to be confused with UTC, since this zone observes Summer Time
Asia/BeijingChina Standard Time
Asia/CalcuttaIndia Standard Time; observes a 30 minute offset
Australia/SydneySydney time
Pacific/KiritimatiLine Islands time; one of the earliest time zones in the world
Pacific/MidwaySamoa time; one of the last time zones in the world
Atlantic/AzoresAzorian time
America/Argentina/San_LuisWestern Argentina time; one of few modern tripartite IDs
Australia/EuclaAustralia Central Western time; observes a 45 minute offset

Specify the use of IANA time zone IDs in standards, protocols, or document formats as the identifier for time zones.

Avoid special purpose time zone IDs, such as those beginning withEtc/.

Usecontinent/city IDs in preference to legacy zone IDs such as those starting withUS/.

3.3.4Selecting the Time Zone using the Local Time Offset

Most countries are either small enough in area or, for practical reasons, choose to observe only a single time zone for the entire country. This means that knowing the region or country of the user is frequently sufficient to identify the time zone of the user as well. At the time this document was published, only twenty countries had more than one observed time zone. These countries are: Argentina, Australia, Brazil, Canada, Chile, Democratic Republic of the Congo, Ecuador, France, Greenland, Indonesia, Kazakhstan, Kiribati, Mexico, Micronesia, Mongolia, New Zealand, Portugal, Russia, Spain, and the United States.

Some special cases exist within this list:

  • Countries with maritime or overseas possessions Chile, Ecuador, France, New Zealand, and Portugal each have islands or other wide-ranging geographic areas far from the main part of the country. For example, Easter Island is part of Chile, the Galapagos Islands are part of Ecuador, and the Azores are part of Portugal. These offshore possessions are the source of additional time zones in each of these countries.
  • France France is a special case of the above. There are several regions that are part of France, even though they might have their own ISO 3166-1 code. These include Reunion Island (in the Indian Ocean) and French Guiana (in South America). Additionally, French Polynesia is divided into three time zones.

Within each of the countries that observe multiple time zones, knowing the current offset and current time will usually allow you to determine the time zone accurately. An exception to this is the United States: there exist some regions, such as Arizona, whose time zone cannot be determined strictly from the current time, country/region code, and offset, although an inferred time zone will always work for current time applications (not future and past times).

3.3.5Stability of time zones

Time zones, their rules, offsets, and observation (or non-observation) of summer time are controlled by a variety of international agreements, as well as national, regional, sub-national, and local governments. This can mean that neighboring areas that might otherwise share a UTC offset, even those with similar latitude (or shared borders) can have differing rules, such as those governing daylight-savings. Sometimes local authorities will change the boundaries of a zone or the offset used by a given region. Or they can make one-time changes to accommodate a special event (such as when hosting the Olympics). The time zone database tracks past changes so that applications can accurately computewall time for past and future events.

Because there are many governing bodies acting independently, the time zone database is not stabilized. New rule changes or updates to historical records are introduced into the database as they are made known (such as due to legislative action). There is no specific release cycle: updates can happen at any time. When changes affect future events, computing systems have to be updated lest their clocks show the wrong local time for a given region or compute the wrong results for events affected by the change.

3.4Representing Dates and Times in Data

There are several ways to represent time data, which vary in suitability according to an application needs.

3.4.1Incremental Time

Incremental time measures time using fixed integer units that increase monotonically from a specific point in time called theepoch. Most programming languages and operating environments provide data types and APIs that use incremental time to represent or operate on datetime values. Incremental time is not usually seen directly by users. Instead, the incremental time value is formatted into a familiarwall time representation for human consumption.

The most common form ofincremental time is counted in milliseconds (or, occasionally, nanoseconds) in the Unix Epoch. In this system, the value0 represents midnight, January 1, 1970 in the UTC time zone. Negative numbers represent datetime values earlier than this moment, while positive numbers denote later moments in time. The [ISO8601] representation of this would be1970-01-01T00:00:00.000Z. Examples of this form of incremental time include:

  • Java:java.util.Date
  • C/C++:time_t
  • #"#dfn-timeline" data-link-type="dfn">timeline.

    This also means that incremental datetime values are indepedent of (and generally do not encode) their originating time zone. This is because the monotonic time in the UnixEpoch is the same everywhere at any given instant. Each incremental time value can be transformed for display using variouschronologies, time zone rules or,local time offsets.

    Note

    Not all incremental time values are tied to specificepoch. A system's clock might be counting from the last time the hardware clock was restarted or some other event. Date values close to January 1, 1970 are often due to an incremental time value of0 or due to malfunctions in or failure to set the system clock.

3.4.2Field-Based Time

Afield-based time divideswall time into separate field values such as year, month, day, hour, minute, second, etc. Field-based times may or may not be tied to either UTC or the local time zone—or may be indeterminate. Field-based times are also typically tied to a specific calendar (such as the Gregorian calendar). The formats described by the [ISO8601] standard are field-based.

Somefield-based time values are on thetimeline (that is, "zone-dependent" values) while others arefloating time values. It's important to distinguish between these two when working withfield-based time to avoid inappropriate conversion of the value.

Example 5: A field-based time type

Thetm structure in the C programming language is an example of a field-based time.

#include <time.h>#include <stdio.h>int main(void){  struct tm t;  time_t t_of_day;  t.tm_year = 2011-1900; /* 1900 based */  t.tm_mon = 0;   /* January: zero based! */  t.tm_mday = 3;  /* the third */  t.tm_hour = 0;  /* midnight */  t.tm_min = 0;   /* midnight */  t.tm_sec = 0;   /* midnight */  t.tm_isdst = 0; /* no DST in January */  t_of_day = mktime(&t);  /* convert the tm struct to an incremental time_t */  printf(ctime(&t_of_day));  return 0;}

A field-based time may or may not include information about the time zone being used. In a purely numeric representation, such astime_t, sometimes only the current UTC offset is provided.

Note

Some modern APIs and data structures mix aspects ofincremental time andfield-based time. Notably Java'sjava.time Temporal types and the proposed Temporal types in JavaScript provide types likeInstant that are "pure"incremental times as well as more complex types, such asZonedDateTime, which can be instantiated and accessed by field or incrementally. It's a lot easier for most humans to work with field-based values.

3.4.3Floating Time

Afloating time is a date or time value in acalendar that is not a specificinstant in time. Applications and data formats use afloating time value when thewall time is more important to the value than putting the event onto atimeline. Generally, a floating time value will include only the date (2024-01-27) or only the time (13:00:00), but datetime values (2024-01-27T13:00:00.000) are sometimes also needed.

Floating time values are used when a given value's localwall time expression needs to stay constant, regardless of the viewing user's time zone. For example, if your birthdate wereJune 1, 1980 this might be represented as thefloating time1980-06-01. It does not matter if you view this date in Tokyo, London, or San Francisco: you always want the displayed value to remain constant. Time values that float can include things such as hours of operation as a policy, rather than for a specific location.

Floating time values are often serialized in various ISO8601 formats by omitting thelocal time offset (or time zone identifier, such asZ forUTC). Data types for floating time values are less common in programming languages and operating environments. Errors are often the result when a floating time value is deserialized into into anincremental time type, which ties the value to UTC.

Note
Floating times have different names in different specifications. [HTML] calls afloating time value alocal date and time. JavaScript Temporal calls these valuesplain dates or times.
Example 6: Floating Time

For example, the French national holiday Bastille Day (Fête Nationale) is observed on July 14th each year. Thus the 2022 occurence might be represented by the value2022-07-14. However, the observation of the holiday isn't tied to any specific location. Instead, its meaning "floats" based on locally observed midnight.

France has a number of overseas departments which do not share a time zone with Metropolitan France. In this example, we'll look at three French time zones:Europe/Paris,Pacific/Noumea (the time zone used in New Caledonia), andPacific/Tahiti (one of the timezones in French Polynesia).

New Caledonia is one of (but not the) first time zones in France to observe the holiday. Tahiti is one of (but not the) last in France to observe it. The table below shows the dates and times in each of the time zones as Bastille Day is observed around the world. Notice that some of theincremental time values that are "Bastille Day" in one time zone are either before "Bastille Day" starts or after it ends in the other time zones:

Europe/ParisPacific/NoumeaPacific/Tahiti
Europe/Paris2022-07-14
midnight
2022-07-15
midnight
2022-07-13 3PM2022-07-14 3PM2022-07-14 noon2022-07-15 noon
Pacific/Noumea2022-07-14 9AM2022-07-15 9AM2022-07-14
midnight
2022-07-15
midnight
2022-07-14 9PM2022-07-15 9PM
Pacific/Tahiti2022-07-13 noon2022-07-14 noon2022-07-13 3AM2022-07-14 3AM2022-07-14
midnight
2022-07-15
midnight

3.4.4Converting between representations

Sometimes aproducer will emit afloating time value when theconsumer expects or requires anincremental time value. In other cases, aconsumer might need to convert a local or otherwise incremental time value into a floating date or time.

Tofloat a date or time value means to remove anincremental time value from thetimeline by deleting any associated time zone and zone offset information from the value.

One common reason to float a value is if the data type used to collect or process the value is an incremental type (such as anInstant or JavascriptDate) but the value isn't. For example, if you received a user's birth date as aDate object. Removing the time zone or offset makes it easier to format the value later without the field values changing incorrectly.

Tounfloat a date or time value means to attach afloating time value to thetimeline by adding a time zone or zone offset to the value.

One common reason to unfloat a value is that the serialized value might not contain an offset but the value needs to be compared to other incremental values or displayed to the user in local time.

Values received without a time zone or zone offsetSHOULD generally be treated as if they are in UTC. SpecificationsSHOULD provide guidance on how to handle these values. ImplementationsMAY use some other value for the offset, such as the user agent's local time zone, but only if there is a good reason to do so.

3.4.5Comparing representations

Conversion between or operation on data sets that mix values with and without time zones orzone offsets presents certain problems. If one wishes to write a comparison between the value of afloating time value and a non-floating value, then the two values have to be reconciled to us the same reference point on thetimeline.

Example 7: Values with and without zone offsets
2005-06-07T13:14:27Z  2005-06-07T11:00:00

If one wishes to write a comparison between the value of<aDateTime> and<bDateTime>, then the two values must be reconciled to use the same reference point.<aDateTime> uses UTC and can easily be converted to computer time or shifted to another zone offset.<bDateTime> contains no indication of the zone offset. It might be UTC or any other value (currently up to 14 hours different in either direction from UTC).

It is good practice to use a time zone identifier or at least an explicit zone offset wherever possible. If one is not available, use UTC as the implicit zone offset for conversions of this nature. This is because the values are exactly centered in the range of possibilities and because representation internally (as computer time) is usually based on UTC. Since a single reference point has been used it might be possible to unwind the change later even if an erroneous conversion has taken place. When working with multiple documents from various sources, the "implicit" offset of the document may vary widely from that of the implementation doing the processing. If UTC is widely used, the chances of error are reduced.

Content and query authors are warned that comparing or processing data sets that contain both date and time values with and without time zones or zone offsets may produce odd results. Such processing should be avoided whenever possible. Generating content that omits zone offset information (where it exists) is a recipe for errors later. Of course, data such as the SQL types cited earlier and which are meant to represent wall time, should continue to omit the zone offset. Query writers can check for the presence (or absence) of zone offset and should do so to modify dates and times explicitly (instead of allowing implicit conversion) whenever possible.

When comparingfloating times toincremental times, use UTC as the time zone.

3.4.6Working with mixed representations

Incremental time andfield-based time differ in the way certain operations work. For example, incremental times can often be directly compared: their integer values determine which is earlier or later.Field-based times have to be normalized and their individual fields compared.

Field-based times are often optimized to allow for various kinds of adjustments to be made to a value while minimizing the chances for error. For example, to set the date2005-08-30 forward by one day, an implementation can add 'one unit' to the "day" field and adjust the day, month, and year fields as appropriate to the calendar system. In incremental time, a similar operation might be performed by incrementing the value by24 hours * 60 minutes * 60 seconds * 1000 milliseconds, which is one "logical day". However, there can be errors when a particular day has more or fewer seconds in it (such as occur during daylight saving transitions) or when the unit has a variable size, such as when adding a month or a year, since those fields have variable numbers of days in them.

Bear in mind that rolling fields forwards or backwards infield-based times can be tricky. For example, Feburary does not always have the same number of days in it. Or consider the problem of incrementing the month forward by one in the date2011-01-30.

Serializations of date/time values tend to behave as-if they were field-based, in that they provide human-readable values tied to a specificchronology (typically theISO Chronology). The most familiar example of such a serialization scheme is [ISO8601], along with its many flavors and interpretations, such as [RFC3339] or [XMLSchema-2]. The SQL data typesdate,time, andtimestamp arefield-based time values which are intended to be zone offset independent: they are actuallyfloating time values! The SQL data typetimestamp with time zone is actually the type that should be used forincremental time values ("timestamps").

By contrast with SQL types, programming languages tend to useincremental time for their primitive time types. They convert to and from field-based serializations demand. As a result, users might not be clear about the differences between these types or can accidentally create a mixture of different representations. For example, a Java programmer using JDBC might access a field in a SQL query using the classjava.sql.Date. This class represents the value as anincremental time in UTC. This adds information inappropriately tofloating time values or can remove zone-offset information from the originalfield-based time value.

Databases can useincremental time or either zone offset-dependent or independent field-based structures internally. For example, Oracle databases treat atimestamp field as though it is in the local time zone of the database instance. The combination of application and database time zones coupled withimplicit conversions betweenincremental time andfield-based time values can result in date/time values changing meaning without the user intending it.

In [XMLSchema-2], as with SQL, dates and times are expressed usingfield-based time. The date or time can express the zone offset from UTC (for example using a format such as08:00:00+01:00).UTC is indicated by the letterZ (for example08:00:00Z). The zone offset can also be omitted (producing afloating time value).

Properly speaking, an XML Schema date or time value with a zone offset is field-based/zone offset dependent and one without is field-based/floating.

If the two types are mixed, then the interpretation of the zone offset is not adequately specified in XML Schema. In [XPATH-FUNCTIONS], the interpretation is implementation-defined and is based on an implicit zone offset. This is usually either UTC or whatever the local time offset of the host environment is. The presence or absence of the zone offset in the XML Schema serialized representation might not be indicative of the original data's intention because of the confusion described above. Proper comparisons or processing rely on normalizing all date and time values intofloating time or zone offset-dependent (field-based zone-dependent) forms and never mixing the two in a particular operation.

3.4.7Serializations

Date/time values often need to be serialized (converted to some string representation) for exchange in various document formats and protocols. Sometimes these serializations can be produced from or used to instantiateincremental time,field-based time, orfloating time datatype values directly. Precisely which serialization to use depends on the application'suse case and available standards. Serializations that use time zone IDs instead of relying on offsets areRECOMMENDED.

Note

The serializations in this section that utilized time zone IDs (and not just offsets) were only recently standardized, in [RFC9557]. Other standards, such as XMLSchema, cannot currently represent these values.

Type Being SerializedSerialization to UseDescription
Instant, Timestamp, Date2007-01-01T01:00:00.000ZAnincremental time (instant on the timeline) with UTC offset.
OffsetDateTime2007-01-01T01:00:00.000+01:00Anincremental time with an explicit offset from UTC. Zoned Instant is preferred.
Zoned Offset DateTime2007-01-01T01:00:00.000+01:00[America/Chicago]Anincremental time with an offsetand a specific time zone. The time zone should be used when formatting the value for display. Note that the offset and the time zone do not have to match. Generally the offset date time is converted to an instant on the timeline using the offset provided and then the time zone specified is attached to that moment.
Zoned Instant2007-01-01T01:00:00.000Z[America/Chicago]Anincremental time with a specific time zone that should be used when formatting the value for display.
Zoned Local Date Time2007-01-01T01:00:00.000[America/Chicago]Afloating time value with both a date and a time plus a specific time zone that should be used when displaying the time value. This serialization is equivalent to a zoned offset date time when the offsets match.
Local Date Time2007-01-01T01:00:00.000Afloating time value containing both a date and a time.
Local Date2007-01-01Afloating time with a date but no time component.
Local Time00:00:00.000Afloating time with a time but no date component.
Year-Month2007-01Afloating time value containing only a year and a month. Similar to [XMLSchema-2]gYearMonth.
Year2007Afloating time value containing only a year. Similar to [XMLSchema-2]gYear.
Month-Day01-01Afloating time value containing only a month and day. Similar to [XMLSchema-2]gMonthDay.

4.Use Cases

There are a number of ways applications can use date and time values. In this section we examine the different common use cases and the serializations or data structures to use for each.

4.1Timestamps

Use an incremental time value such as theInstant orDate type for timestamp values.

This is the most common use case: use a timestamp unless you have a reason not to. If your application can accurately generate incremental and/or field-based times based on UTC and the events are not tied to specific local time, all that is needed is the timestamp value itself. That is, if your application never needs to recover what the localwall time was when event occurred and only cares about relative ordering of events. For example, if you merge log files from many machines together or if you are recording events in a log, a timestamp is perfectly adequate. For these types of time events, an Instant is sufficient.

It is usually desirable to normalize timestamp values to UTC (or, less commonly, a specific UTC offset) so that separate series of data can be easily compared and merged. Information about local offset may be valuable in recovering the actual wall time, but time zone rules are probably only rarely interesting.

When in doubt, useUTC for serializing, storing, and exchanging date and time values.

Bear in mind that thelocal time offset doesn't change the relationship of a datetime value to thetimeline. Serializing timestamp values with an offset makes the values more difficult to work with, particularly in systems where multiple offsets might be in use.

In other use cases, we'll see that storing thetime zone is valuable or even required for consistent results. However, this never applies to timestamp values. The only thing that storing thetime zone might provide is the originatingwall time.

4.2Handling past or future events

Many applications need to work with events that have already occurred, events in the future, or both. When working with these types of values, additional care needs to be used to avoid problems with the way that time zones interact with events.

Example 8: Example of a time zone change affecting a future event

For example, consider an application that defines certificates. Each certificate has a date-time value that is the "start of authority" (validFrom) moment and a date-time value that is the "end of authority" (validUntil) moment.

Imagine that Certificate A is generated in the time zoneAmerica/Los_Angeles. This time zone has a raw offset from UTC of 8 hours and it currently observesdaylight savings time between a date in March and a date in November. Certificate A is generated with avalidUntil value of2035-07-12T12:00:00-07:00, reflecting the observation of DST during the month of July.

After Certificate A was generated (but before it expires), imagine that the time zoneAmerica/Los_Angeles decides to stop observingdaylight savings time. Then imagine a user wishes to generate Certificate B to replace Certificate A when it expires. If the new certificate is valid "from noon on 12 July", it might be serialized as2035-07-12T12:00:00-08:00, because the time zone's offset will not be in DST any longer. Notice that this is one hour later than the actual expiration of Certificate A.

4.2.1Past-only Events

YouSHOULD useZonedInstant type for past-only events.

YouMAY useZonedInstant,ZonedLocalDateTime orZonedOffsetDateTime types for past events.

For an application that deals only with events that occurred in the past (with no future events) and for which you need to know what the wall time was, thelocal time offset of the event may be necessary additional data. Note that the time zone also provides thelocal time offset and is, thus, an acceptable substitute.

Once an event is in the past, itslocal time offset toUTC becomes fixed. Therefore an incremental time with an offset can always producewall time in a givenchronology.

Althoughlocal time offset is sufficient, knowing the specific time zone allows the application to reconstruct the time and its relationship to other time values and is usually more convenient when formating the value for display. For example, without the time zone identifier, it's not possible to accurately include the time zone's name or abbreviation into the display.

4.2.2Past and Future Events

YouSHOULD useZonedInstant type if your application can have events in the future.

For an application that deals with both past and future events (for example, if you have a calendar or a meeting schedule), you will need the time zone (and not merely thelocal time offset) to ensure proper time computation. This is because a future event'swall time depends on time zone-related information, such as summer time transitions.

One issue with future events is that rules for the event's associated time zone canchange from time to time and these changes can require an application to update affected data records in order to meet the user’s expectations. This is because many systems actually store or depend on using anincremental time value for date/time related operations (such as scheduling or notifications). When the time zone rules change, the corresponding the incremental time value needs to be checked or updated if thewall time of the event is expected to stay the same. Seeabove for an example.

Note

Applications that pre-compute or storeincremental time values for future events might need to refresh the values after the local runtime's copy of the time zone database is updated, since time zone rules affecting these values might have been updated.

4.2.3Recurring Events

A recurring event, such as a regular meeting, is usually defined by a set of rules that express a user's intent. In many cases, the user intends for the event to recur at a specific localwall time in a specific time zone. Each iteration is thus apast or future event.

Each iteration of the event will need to compute a specific (incremental time value) start time and this value will depend on the governing time zone's rules regardinglocal time offset, summer time transitions, and the like. It is important to use the time zone to perform these computations, as this avoids problems with assuming that the number of units between events (such as hours in a week or minutes in a day) is fixed. It can also help avoidghost times.

4.2.4Floating Time Values

YouSHOULD use the appropriate floating time type, such asLocalDateTime (for values with both date and time),LocalDate (for date values), orLocalTime (for time-only values) for values that are not tied to a specific offset or time zone rules.

If your application deals with a date or time value that is not tied to a specific local interpretation or which needs to be interpreted as a different range of incremental time values in different locations, serializing the value without an offset or time zone identifer communicates that the value is afloating time.

Such applications are more common than they first appear. We've already seen examples in this document, such as a list of holidays or a user's birth date. Any "anniversary" type of date (hire date, termination date, wedding date, etc.) is generally best representated afloating time value. Another application is when you collect statistics usinginstants but need to group them into durable time buckets byfloating the values.

4.3Additional Considerations

4.3.1General Recommendations

Whenever possible, useUTC or choose a consistent time zone when creating time-based content or data value so that values from discrete sources can be compared more readily.

Example 9

It is much easier to work with and debug data values that can be compared visually. When values use different offsets or time zones, the user has to mentally translate the value. This can lead to mistakes. When you read the "mixed offset" list of timestamps below, is it easy to spot that the last two items are identical or that the first three are different?

Mixed OffsetsSame value converted to UTC
2007-01-01T01:00:00.000-01:00
2007-01-01T01:00:00.000Z
2007-01-01T01:00:00.000+01:00
2006-12-31T23:00:00.000-01:00
2007-01-01T02:00:00.000Z
2007-01-01T01:00:00.000Z
2007-01-01T00:00:00.000Z
2007-01-01T00:00:00.000Z

Bear in mind best practices to assist users in selecting their time zone, including keeping track of their preferences.

Some best practices when implementing time zone selection and management:

  • Allow the user to choose a time zone and keep it associated with the user's session or profile if possible.
  • Consider using exemplar cities to help users identify the time zone.
  • Use the country as a hint, since most countrieshave only a single time zone.
  • Omit historical time zones whenever possible.
  • Use IP-geolocation, cellular radio country code, GPS data, or other external data sources if available.

4.3.1.1Working with XQuery/XPath/XSLT

If you are a users of specifications such as XQuery [XQUERY-10] and XSLT [XSLT-30] and other, similar, standards, in addition to the guidelines found elsewhere in this document, take the following into account even if time-zone-sensitive data is rarely used. Sooner or later some data will be affected by the issues described.

Use an explicit zone offset with date, time, and dateTime types, if possible. Include an additional field indicating the time zone if one is not provided.

Do not apply operations based on date or time types (such as indexing) to collections of data in which some data items have zone offset information while other data items do not have zone offset information.

If you have data that includes implicit and fixed explicitlocal time offsets, before applying any date- or time-sensitive operations, adjust the zone offset of the implicit data to UTC with functions for zone offset adjustment, cf.this section inXQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition).

If you have data that contains both implicit and fixed explicitlocal time offsets and you do not want to adjust the data subset which already has a zone offset, make sure that you recognize this data subset, for example via thecomponent extraction functions [XPATH-FUNCTIONS].

4.3.2Leap Seconds

One quirk of timekeeping is the need for leap seconds. The Earth's rotation is not even and, in general, is slowing down. To keepobserved time andincremental time in sync, the [International Earth Rotation Service] occasionally mandates a "leap second". A leap second usually occurs once or sometimes twice per year and always takes the form of an additional second added to the last minute of the day. Usually the leap second is added to December 31st or June 30th.

Most incremental time values (do not keep track of leap seconds in their incremental time values. What happens is:

  1. Eventually, system clocks are updated externally by the user or via a service such as NTP. Most computer clocks exhibit some amount of clock drift anyway, so this sort of maintenance is not unusual.
  2. No list is kept of past or future leap seconds (and no list exists for dates preceding the advent of leap seconds in 1972), so software often doesn't include leap seconds when calculating the difference between two time values. For example, the difference between 12:00:00 Noon on December 31st and 12:00:00 Noon on the following January 1st will always be 86400 seconds, even if a leap second was mandated for the intervening midnight.
  3. There may be no way to represent a leap second time value using your local incremental units and may not be a means of representing a leap second using field-based units. For example, while Java'sjava.util.Calendar class allows for a "61st" second of a minute to accommodate leap seconds, if you set a Java Calendar to the equivalent ofDecember 31, 2008 23:59:60 UTC (a particular leap second value) and then convert that to ajava.util.Date in order to print it out, you might see: "January 1, 2009 00:00:00 UTC". This is because theDate object is anincremental time and the code formatting the value doesn't know about the leap second.

If your application cares about or is sensitive to leap seconds, special care must be taken to deal with the loss of leap second precision.

A.References

A.1Informative references

[BCP175]
Procedures for Maintaining the Time Zone Database. E. Lear; P. Eggert. IETF. February 2012. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc6557
[CLDR]
Unicode Common Locale Data Repository. Unicode Consortium. URL:https://cldr.unicode.org/
[HTML]
HTML Standard. Anne van Kesteren; Domenic Denicola; Dominic Farolino; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL:https://html.spec.whatwg.org/multipage/
[i18n-glossary]
Internationalization Glossary. Richard Ishida; Addison Phillips. W3C. 17 October 2024. W3C Working Group Note. URL:https://www.w3.org/TR/i18n-glossary/
[ISO8601]
Representation of dates and times. ISO 8601:2004.. International Organization for Standardization (ISO). 2004. ISO 8601:2004. URL:http://www.iso.org/iso/catalogue_detail?csnumber=40874
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc2119
[RFC3339]
Date and Time on the Internet: Timestamps. G. Klyne; C. Newman. IETF. July 2002. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc3339
[RFC9557]
Date and Time on the Internet: Timestamps with Additional Information. U. Sharma; C. Bormann. IETF. April 2024. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc9557
[UAX35]
Unicode Locale Data Markup Language (LDML). Mark Davis et al. Unicode Consortium. 23 October 2020. Unicode Technical Standard #35. URL:https://www.unicode.org/reports/tr35/tr35-61/tr35.html
[XMLSchema-2]
XML Schema Part 2: Datatypes Second Edition. Paul V. Biron; Ashok Malhotra. W3C. 28 October 2004. W3C Recommendation. URL:https://www.w3.org/TR/xmlschema-2/
[XPATH-FUNCTIONS]
XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition). Ashok Malhotra; Jim Melton; Norman Walsh; Michael Kay. W3C. 14 December 2010. W3C Recommendation. URL:https://www.w3.org/TR/xpath-functions/
[XQUERY-10]
XQuery 1.0: An XML Query Language (Second Edition). Scott Boag; Don Chamberlin; Mary Fernandez; Daniela Florescu; Jonathan Robie; Jerome Simeon. W3C. 14 December 2010. W3C Recommendation. URL:https://www.w3.org/TR/xquery-10/
[XSLT-30]
XSL Transformations (XSLT) Version 3.0. Michael Kay. W3C. 8 June 2017. W3C Recommendation. URL:https://www.w3.org/TR/xslt-30/


[8]ページ先頭

©2009-2025 Movatter.jp