Science
ISO
ISO 8601

ISO 8601 (International Standard for the Representation of Dates and Times)

Introduction

ISO 8601 is an international standard for the representation of dates and times. It is the most common way to represent dates and times in computer systems. It is used in many different fields, such as computer programming, electronics, and telecommunications.

ISO 8601 é um padrão internacional que define um formato reconhecido internacionalmente para representar datas e horas. O formato básico é ano-mês-dia para datas e horas-minutos-segundos para horas. Por exemplo, 27 de setembro de 2022 às 18h é representado como 2022-09-27 18:00:00.0002. Esse formato facilita a escrita dos números diretamente um após o outro.

A principal característica do formato de data e hora da norma ISO 8601 é que a informação de data e hora seja ordenada a partir do valor mais significativo ou, em termos simples, do maior (o ano) para o menor (o segundo).

Fusos horários em ISO 8601 são representados como hora local (sem especificar o local), como UTC ou como um deslocamento de UTC. A hora local é assumida se nenhuma informação de relação com UTC for dada. O UTC é expresso como "Z" e o deslocamento é expresso como "+hh:mm" ou "-hh:mm" como a diferença de tempo do UTC. Por exemplo, 2022-09-27 18:00:00.000Z é o mesmo que 2022-09-27 21:00:00.000+03:00.

Os formatos são mostrados a seguir. A forma de representação é rigidamente como mostrado com todos seus elementos componentes e pontuação. Observe que a letra "T" aparece literalmente na representação, para indicar o início de um elemento de tempo, conforme descrito na ISO 8601.

Ano: YYYY (p.ex. 1997) Ano e mês: YYYY-MM (p.ex. 1997-07) Data completa: YYYY-MM-DD (p.ex. 1997-07-16) Data completa com horas e minutos: YYYY-MM-DDThh:mmTZD (p.ex. 1997-07-16T19:20+01:00) Data completa com horas, minutos e segundos: YYYY-MM-DDThh:mm:ssTZD (p.ex. 1997-07-16T19:20:30+01:00) Data completa com horas, minutos, segundos e uma fração decimal de segundo YYYY-MM-DDThh:mm:ss.sTZD (p.ex. 1997-07-16T19:20:30.45+01:00)

onde:

 YYYY = quatro dígitos para o ano
 MM   = dois dígitos para o mês (01=Janeiro, etc.)
 DD   = dois dígitos para o dia do mês (de 01 até 31)
 hh   = dois dígitos para horas (de 00 até 23) (am/pm não é permitido)
 mm   = dois dígitos para minutos (de 00 até 59)
 ss   = dois dígitos para segundos (de 00 até 59)
 s    = one or more digits representing a decimal fraction of a second
 TZD  = designa o fuso horário (Z ou +hh:mm ou -hh:mm)

Date and Time

The ISO 8601 standard defines a number of different ways to represent dates and times. The most common way is to represent dates and times as text strings. The following example shows how to represent the date and time 2019-10-31 12:00:00 in ISO 8601 format:

2019-10-31T12:00:00

The following example shows how to represent the date and time 2019-10-31 12:00:00 in ISO 8601 format with a time zone:

2019-10-31T12:00:00+02:00

Date

The following example shows how to represent the date 2019-10-31 in ISO 8601 format:

2019-10-31

Time

The following example shows how to represent the time 12:00:00 in ISO 8601 format:

12:00:00

Time Zone

The following example shows how to represent the time zone +02:00 in ISO 8601 format:

+02:00

Unix Timestamp (Epoch)

Unix dates represent time as the number of seconds since January 1, 1970, 00:00:00 UTC, also known as the Unix epoch. Unix dates are used in Unix-based operating systems and are commonly used in programming for time calculations and comparisons.

The Unix timestamp is a way to represent a point in time as a number. The Unix timestamp is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. The following example shows how to represent the date and time 2019-10-31 12:00:00 as a Unix timestamp:

1572528000 seconds # 2019-10-31 12:00:00

You could use Unix dates to represent the timestamps of these events and perform time-related calculations (such as subtracting one timestamp from another) to determine the time difference between them.

Format

The format of Unix timestamps is a 32-bit signed integer, where the integer value represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. Unix timestamps do not include fractional seconds, so their resolution is limited to whole seconds.

Here is an example of a Unix timestamp in decimal notation: 1615304312, which represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC, up to the time when this example was created.

Unix Timestamp Limitations

Unix timestamps have a limited range: Unix timestamps are represented using a 32-bit signed integer, which means they have a limited range of valid values. Specifically, the maximum value that can be represented is 2^31-1, which corresponds to January 19, 2038, 03:14:07 UTC. After this point, Unix timestamps will "roll over" and start counting from negative values, which can cause issues for programs that rely on Unix timestamps for time-related calculations.

In some newer operating systems, time_t has been widened to 64 bits. This expands the times representable by approximately 292 billion years in both directions, which is over twenty times the present age of the universe per direction.

Expanding the range of Unix timestamps to 64 bits allows them to represent a much larger range of valid values, up to 2^63-1 seconds after January 1, 1970, 00:00:00 UTC. This corresponds to a date far in the future, well beyond the year 292,277,026,596 AD.

To represent Unix timestamps using 64 bits, the timestamp value is simply stored as a 64-bit integer, with the integer value representing the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC, and the fractional part of the timestamp representing microseconds or nanoseconds.

The choice of 32 bits for Unix timestamps was made when the Unix operating system was first developed in the early 1970s. At that time, 32 bits was considered to be a sufficient number of bits to represent time values for most applications.

In the early days of Unix, computers had much less memory and processing power than they do today, and storage space was also much more limited. Using 32 bits for timestamps was a space-saving measure that allowed Unix systems to store and manipulate time values using a relatively small amount of memory.

Additionally, at the time Unix was developed, it was not anticipated that Unix timestamps would still be in use decades later. The year 2038, when the 32-bit Unix timestamp will roll over, was far beyond the expected lifespan of most computer systems.


NTP (Network Time Protocol)

The Network Time Protocol (NTP) is a networking protocol for clock synchronization between computer systems over packet-switched, variable-latency data networks. NTP is used to synchronize all the clocks in a network. NTP is one of the core protocols of the Internet protocol suite. It operates over UDP port 123.

NTP is a protocol used for time synchronization between computers on a network. It is used to synchronize the clock of a computer with a reference time source, such as a GPS receiver or an atomic clock. NTP represents time as the number of seconds since January 1, 1900, 00:00:00 UTC, with fractional seconds represented as a 32-bit fixed-point number.

Fractional Seconds

Let's say you have two computers on the same network, and you want to synchronize their clocks using NTP. The first computer has a clock that is currently set to 10:30:00.000000 (i.e., 10:30 AM and 0 milliseconds), while the second computer's clock is set to 10:30:00.500000 (i.e., 10:30 AM and 500 milliseconds).

When the first computer sends a NTP packet to the second computer, the packet will contain the current time of the first computer, which is 10:30:00.000000. The second computer will then compare this time to its own clock and adjust its clock accordingly to synchronize with the first computer.

Notice that NTP uses fractional seconds (i.e., up to 32 bits after the decimal point) to represent time, which allows it to achieve a higher resolution than Unix dates. In the example above, NTP can distinguish between two times that are only 500 microseconds apart (i.e., 0.5 seconds), while Unix dates can only represent time in whole seconds, which means it cannot represent the 500 microsecond difference between the two clocks.

Format

The format of NTP timestamps is a 64-bit fixed-point number, where the integer part represents the number of seconds that have elapsed since January 1, 1900, 00:00:00 UTC, and the fractional part represents the fraction of a second that has elapsed since the integer part. The fractional part is represented using 32 bits, which allows for a very high resolution of time.

Here is an example of an NTP timestamp in hexadecimal notation: 0xDEADBEEF.12345678, where 0xDEADBEEF represents the integer part of the timestamp in hexadecimal format (i.e., 3735928559 in decimal), and 0.12345678 represents the fractional part of the timestamp in hexadecimal format.


NTP Vs. Unix Timestamp

While both NTP and Unix dates represent time as a number of seconds, they use different reference points and have different resolutions. NTP has a higher resolution due to its use of fractional seconds, while Unix dates have a lower resolution. Additionally, NTP is used primarily for time synchronization, while Unix dates are used for a wide range of time-related calculations and operations.

Useful knowledge

  • NTP timestamps can be affected by network delays: NTP timestamps rely on accurate time synchronization across the network, so any delays in network transmission can affect the accuracy of NTP timestamps. NTP compensates for these delays using algorithms such as symmetric active/passive mode and intersection algorithms.
  • NTP timestamps can have a very high resolution: NTP timestamps include a 32-bit fractional part, which allows for a very high resolution of time. This high resolution can be important for applications that require very precise time synchronization.
  • Unix timestamps can be affected by time zones: Unix timestamps represent the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC, which means that they do not take into account time zone differences. This can be problematic if you need to perform time-related calculations across different time zones.
  • NTP timestamps can be synchronized across a network: NTP is designed to synchronize clocks across a network, which means that you can use NTP to ensure that multiple devices have a consistent and accurate time. This can be useful for applications that require time synchronization across multiple devices, such as distributed databases or financial trading systems.
  • Unix timestamps can be converted to human-readable dates and times: While Unix timestamps are represented as a numeric value, they can be easily converted to human-readable dates and times using built-in functions in programming languages such as Python and JavaScript. This can be useful for displaying timestamps in a user-friendly format.

Fusos horários

Um fuso horário é uma região do globo que observa um horário padrão uniforme para fins legais, comerciais e sociais. Os fusos horários tendem a seguir os limites dos países e suas subdivisões em vez de seguir estritamente a longitude, porque é conveniente para áreas em comunicação comercial ou outra manter o mesmo horário. Existem 24 fusos horários. Todos os fusos horários são definidos como deslocamentos do Tempo Universal Coordenado (UTC), variando de UTC−12:00 a UTC+14:00. Os deslocamentos são geralmente um número inteiro de horas, mas alguns fusos têm um deslocamento adicional de 30 ou 45 minutos, como na Índia, Austrália do Sul e Nepal.

Os fusos são medidos de acordo com a posição geográfica longitudinal e são divididos por linhas imaginárias chamadas meridianos. A padronização internacional dos fusos horários é o que permite que saibamos os diferentes horários em cada localização geográfica no mundo.

Os diferentes horários definidos pelos fusos são determinados em função da incidência solar em cada localização geográfica. Convencionou-se dividir o planeta em 24 fusos horários, essa divisão foi proposta pela primeira vez pelo engenheiro Sandford Fleming, em 1878.

O Meridiano de Greenwich é o meridiano número zero e para ambos os lados desse meridiano existem outros 12, totalizando 24. Os meridianos que estão à leste são classificados de 1 a 12 e os que estão à oeste, são classificados de -1 a -12. Esse sistema era denominado de GMT (Greenwich Mean Time), mas teve seu nome alterado para Tempo Universal Coordenado (UTC).

Cada meridiano é classificado pela sigla UTC e pelo número do meridiano, por exemplo, UTC + 6 ou UTC - 8. Para leste de Greenwich as horas são adiantadas em uma hora e para o lado oeste as horas são atrasadas em uma hora.

Você pode fazer o cálculo manualmente, subtraindo o deslocamento de UTC do fuso horário mais a leste do deslocamento de UTC do fuso horário mais a oeste. Por exemplo, para calcular a diferença de tempo entre São Paulo (UTC−03:00) e Tóquio (UTC+09:00), você subtrai −03:00 de +09:00 e obtém +12:00. Isso significa que Tóquio está 12 horas à frente de São Paulo.

  • São Paulo (UTC−03:00)

  • Tóquio (UTC+09:00)

  • (-03:00) - (09:00) = +12:00 | Tóquio está 12 horas à frente de São Paulo

  • Los Angeles (UTC−07:00)

  • Moscou (UTC+03:00)

  • (-07:00) - (03:00) = +10 | Moscou está 11 horas à frente de Los Angeles

  • Los Angeles (UTC−07:00)

  • São Paulo (UTC−03:00)

  • (-07:00) - (-03:00) = -04:00 | São Paulo está 4 horas a frente de Los Angeles

  • Fuso horários (opens in a new tab)

  • Time.is (opens in a new tab)