Hi, I’m YourBatman.

Date/time processing is a very common scenario in daily development. If it is just a simple formatting scenario, it is ok. Once it involves the time zone, cross-region and cross-time zone time conversion scenario, and even when there is a bunch of concepts such as GMT time and UTC time, it is always mentally weak and cannot cope with it.

In the information age of the global village, there are more and more multinational enterprises/multinational companies doing business, so the probability of our programmers encountering date/time conversion/display between different time zones increases greatly. For example, it is ok to show Beijing time on the page of the e-commerce platform, but you can’t show Beijing time to Americans, right? Otherwise, Americans would see many orders placed at 1 or 2 a.m. and think it was a ring at midnight.

Java used the Date type for Date/time prior to version 8 and has introduced the JSR 310 Date/time type since version 8. The two systems have different handling methods for local time, time zone, and time zone formatting.

Brother A had A production accident recently because of the date conversion problem across time zones. I thought over the pain and decided to put my experience into writing, so as not to step on this pit in the future, but also to help everyone.

This part will be divided into two articles:

  1. Concepts: GMT, UTC, time zone, timestamp, daylight saving time and other common concepts and background
  2. How Java handles GMT/UTC time, time zone, offset, DAYLIGHT saving time, etc. the

With these two articles finished, I no longer have to worry about date/time bugs. Trust me, these two essays are very collectible.

In this paper, an outline

Version of the agreement

  • The JDK: 8

✍ body

Here are a few date/time concepts that you’ve all heard before, but I’m guessing you don’t understand or even know the difference.

GMT: Indicates the Greenwich mean time

Greenwich (also known as Greenwich) Time, also known as Universal Time (Universal Time), also known as Universal standard Time. Is located inLondon, EnglandThe standard time at the Royal Greenwich Observatory in the suburbs is local time on the prime meridian0 time zoneIn the area.

As we all know, the Beijing time used in the Unification of The Chinese Dynasty is located in the east 8th District (+8) 8 hours from the standard time. What does it mean? For example: if GMT is now 11 am, Beijing Time in China is now 11 + 8 = 19 PM.

To further abstract this formula, it can be expressed as: local time =GMT+ time zone difference

If Beijing is located in the 8TH East zone, the time zone difference N=+8; if New York is located in the 5th West Zone, the time zone difference N=-5. So if it’s 23pm in Beijing, it’s 10am in New York.

Why is Greenwich the standard time?

You may ask why Greenwich stands out so much when everyone has a lumbar disc.

The big picture is this: The beginning of the 19th century, countries around the world began to frequent, and continental Europe, the americas and the Asian continent has its own time zone, to improve the efficiency of communication to avoid confusion, the representatives of the 1884 international conference was held in Washington, dc, to select the Greenwich, London as the center of the world time, and it is responsible for maintaining and computing, begin from 1924, Greenwich Observatory broadcast the time to the world every hour (until 1979).

It’s kind of funny to have a meeting in Washington, D.C., and decide on London, England as the time center

In fact, the main reason for choosing Greenwich was that most ships at that time had already taken Greenwich Meridian as a reference standard. After all, Britain was an empire that never set on the sun, and began to dominate the world at the end of the Great Age of Navigation.

Greenwich observatory authority in the field of timing is very big, such as our nearest one time “wave” : at the time of the cross-century, countries around the world in the 21st century should begin from 2000 or from 2001 began to debate, to quell the debate at the royal observatory Greenwich, eventually, open press conference announcedThe 21st century began in 2001.

The earth’s rotation

The earth rotates from west to east on its axis (the sun rises in the east and sets in the west), so people in the Eastern time zone will see the sun earlier than people in the Western time zone, and so will be a little earlier.

With the prime meridian as the center, according to the earth’s rotation direction, every 15 degrees of longitude divided into a time zone method, the world is divided into 24 time zones: east 1 to east 12, west 1 to west 12, of which east and west 12 span is 7.5° is also called half time zone.

What time zones are there in China?

1. That’s a reasonable wrong answer. It makes sense because China, despite its vast size, uses the same Beijing time across the country, so it’s easy to mistake it for one time zone.

Wrong because if you think about it, China is across 5000+ km, how can you just lie in one time zone? The correct answer is: There are five time zones in mainland China, and the general orientation of each time zone is shown below:

Looking at the picture, you can see clearly why China chose east 8 zone time as the national standard time, right? Yes, just because Beijing is in the east 8th district, even if the map is only the size of a bullet, but it is so aggressive.

The unified time in China is indeed much more convenient for communication, reducing a lot of unnecessary trouble. However, it also brings some “small problems”, such as xinjiang friends (located in east 5/6 district) actually 2-3 hours later than The Beijing time of east 8 district, we usually get dark at 7 o ‘clock when we are ready to have dinner, xinjiang side is still in the sky, it is quite interesting ~

What time zones are there in the United States?

When it comes to time zones, the United States plans to be great again. The United States is similarly vast, spanning four time zones:

As shown in the figure, there are four time zones in total, divided according to the color of the figure (not strictly divided, or it will be embarrassing if the time of the same neighborhood is 1 hour later than you), from right to left:

  1. Eastern Time Zone (ET) : District 5 West, representing cities: Washington, D.C., New York, Miami, etc., also known as New York Time. Beijing time = ET + 13h
  2. Central Time Zone (CT) : West zone 6, representing cities: Chicago, Houston, etc. Beijing time = CT + 14h
  3. Mountain Time zone (MT) : West region 7, representing cities: Denver, Phoenix, etc. Beijing time = MT + 15h
  4. Pacific Time Zone (PST) : District 8 West, representing cities: Los Angeles, Las Vegas, Seattle, etc. Beijing time = PST + 16h

GMT and Http protocol origin

This is a knowledge point I “come across”, and I also share it with you here.

Http 1.1 has strict regulations on date and time transmission formats. The following three formats are supported:

The first format is the standard format for Internet transmission, which is also the current standard. 2 and 3 were designed to be compatible with Http 1.0, and are now mostly obsolete and no one will use them any more, so the only format available is the first one. As an experienced programmer, this format should be familiar.

Another key point: all HTTP date/time stamps must be in Greenwich Mean Time (GMT), no exceptions. For HTTP, GMT is exactly equal to UTC(Coordinated Universal Time).

Of course, all this is done automatically by the browser, which is not responsible for the Http protocol

UTC: World Standard time

Coordinated Universal Time. It takes atomic time as the unit of measurement, and the calculation results are extremely precise and precise. It is more accurate than GMT and must be within 0.9 seconds, with any error greater than that “fixed” by a leap second.

Atomic time: A system of time measurement based on the frequency of electromagnetic oscillations emitted within the atoms of matter. In 2014, the Physics Laboratory in the United States built the most accurate atomic clock in human history, with an error of five billion years of 1s, which is pretty reliable. China’s cesium atomic clock can also ensure an error of less than 1s in 20 million years.

Events: In early December 1979, the World Radio Administration Conference held in Neva adopted a resolution to replace Greenwich Mean Time (GMT) with Universal Coordinated Time (UTC) as the international standard time in radio communications.

The difference between UTC and GMT

UTC and GMT are both called universal Standard time (UTC).

GMT: The old time measure used to measure time based on the Earth’s rotation and revolution. One revolution on the earth’s rotation is a day, and one revolution on the Earth’s revolution is a year. But the earth’s orbit is elliptical:

Later, it was discovered that the earth’s rotation time was not constant, resulting in days that were longer and days that were shorter. This gave the impression that time was not “precise”, so there was an urgent need for a more accurate way to keep time, and UTC was born.

UTC: Atomic clocks were invented in 1967. It is truly standard time, based on the length of seconds defined by atomic clocks. UTC time assumes that a solar day (day) is always a constant 86,400 seconds (24 hours).

UTC is the coordinated time. It means: Everything is based on me, everything is like me. So there’s nothing wrong with calling it Universal Standard time, while GMT is more appropriately called Greenwich Mean Local Time (also known as old Standard Time).

The link between UTC and GMT

In most cases, UTC time is interchangeable with GMT time. Many students on the zhang2 monk puzzled, they are not the same?

Not really. UTC is a reference to standard time. Time zones such as GMT, ET, PST, CST, etc. GMT can be converted directly to UTC simply because GMT happens to be the time in the 0 zone and is numerically equivalent to UTC. It looks the same, but keep the concept separate.

UTC and offset

In everyday life, the time we use must be the local time. In the days when GMT was only available, local time was calculated from the time zone. Now UTC is the standard reference, so local time is represented by UTC and Offset:

The offset can be expressed as UTC – or UTC +, followed by hours and minutes. For example, UTC +9:30 indicates Australian Central Standard time, and UTC +8 indicates Chinese standard time. The common expression of offset is ±[hh]:[mm], ±[hh][mm], ±[HH].

For example, if UTC time is now 10:30 Z (z means offset =0), then Beijing time is now 1630 +0800 (4:30 PM), which corresponds to New York time 0530-0500 (5:30 am).

Note: in the WORLD of UTC, there is no concept of time zones, but offsets (a time point followed by an offset is a proper UTC time), which is not directly related to the time zone

As you can see, the offset is very fine-grained with minute level control. There are only 24 time zones in the world (accurate to the hour only), but the offsets are “infinite”. Of course, in order to facilitate communication, the Time and Date Alliance aggregates the offsets of major countries/cities in the world and gives them a Time zone name for communication. There are hundreds of them in total. Part of the screenshot is as follows:

Offset and country/city name all correspondence, please refer to the url (direct access to without the ladder) : www.timeanddate.com/time/zones

CST

The awkward thing about CST is that it can stand for four different times at once:

  • China Standard Time (CST) : UTC+8:00
  • Central Standard Time (USA) UTC-6:00
  • Central Standard Time (Australia) UTC+9:30
  • Cuba Standard Time UTC-4:00

The meaning of CST depends on the translation, so it depends on the context.

ISO

In time and date it is ISO 8601, is a date/time representation of the specification. A clear and internationally understood format for calendars and clocks was established.

This ISO standard helps eliminate the impact of day-to-day practices, cultures, and time zones on global business. It provides a way to display dates and times in a way that is clearly defined and understandable to both humans and machines. When dates are represented by numbers, they can be interpreted in different ways. For example, 01/05/12 can represent Either January 5, 2012 or May 1, 2012. On a personal level, this uncertainty can be very frustrating, and in a business setting, it can be very expensive. It is very difficult to organise meetings and deliveries, write contracts and buy tickets when the dates are not clear.

ISO 8601 addresses this uncertainty by developing an internationally accepted representation of dates: YYYY-MM-DD. For example, September 27, 2012 would be denoted as 2012-09-27.

Many development languages have some common ISO standard date/time formats built in, such as Java:

  • DATE: yyyy-mm-dd, e.g. “2000-10-31”
  • ISO.TIME: HH:mm:ss.SSSXXX, e.g. “01:30:00.000-05:00”
  • ISO.DATE_TIME:yyyy-MM-dd’T’HH:mm:ss.SSSXXX, e.g. “2000-10-31T01:30:00.000-05:00”.

Daylight saving time

Daylight Saving Time (DST) is also called summer Time. It is a system that artificially regulates local time in order to save energy (encouraging people to go to bed and wake up early, not to waste electricity, and to use natural resources as much as possible in summer when the sun lasts longer). About 40% of the world uses daylight saving time in summer, while the rest of the world only uses standard time throughout the year. Countries that are using daylight saving time: THE United States, the European Union, Russia, etc.

Daylight saving Time varies from year to year (it usually begins on the second Sunday in March). For example, DAYLIGHT saving time in the United States in 2020 will run from March 8, 2020 to November 1, 2020. The idea is to move the clocks forward one hour on 3.8 and back on 11.1.

China did it for a short time in 1986-1992, but it was too troublesome and “scrapped”

Events: Nearly 110 countries around the world currently observe daylight saving time every year. Since March 27, 2011, Russia has been using daylight saving time permanently. It has been moved forward one hour and will not be put back.

The time stamp

In the real world, time is constantly moving forward. If we go back to the beginning of time, it may be when the universe was born or before the universe appeared, but it is certainly impossible for us to find at present. We do not know the exact distance from the origin of time now. So if we want to represent time, we have to artificially define an origin. It is: 0 minutes 0 seconds of midnight GMT on January 1, 1970.

Timestamps generally refer to UNIX time, or the time representation used by UniX-like systems such as Linux and MacOS. Is defined as the total number of seconds since 1970-1-1 0:0:0 UTC time (seconds is a general term for milliseconds, subtle, and nanoseconds).

But one important case: because of leap seconds, it is very likely that when a leap second occurs, the same timestamp will represent two different moments (similar to a clock going back), and leap seconds are not regular enough to be procedurally avoided.

This time needs a special time protocol to ensure, it is: network time protocol.

Network time protocol

Network Time Protocol (NTP) is a Protocol used to synchronize the Time of a computer. It enables a computer to synchronize the Time of its server or clock source (such as quartz clock, GPS, etc.). It can provide high precision Time correction (the difference between the LAN and the standard is less than 1 millisecond, WAN tens of milliseconds), and can be used by encrypted confirmation to prevent malicious protocol attacks.

The purpose of NTP is to provide accurate and robust time service in the disordered Internet environment. NTP is implemented in all major operating systems (Windows /Linux).

✍ summary

In simple terms, Greenwich Mean Time (GMT) can be considered the former standard time, while UTC time is the current world time standard. The time zone is divided by the prime meridian as the center, the east is positive and the west is negative, the local meridian is located in Greenwich, London, England; Daylight saving time (DST) is a local time system (not a global standard), and places that use IT have two special days a year, with one day having only 23 hours and another day having 25 hours.

Having a thorough understanding of these concepts at their source will help us deal with time-related problems. This article introduces a number of date/time concepts, more text, so I suggest you save as a reference book for use.

The next article will continue the content of this article, and introduce how to implement GMT and UTC in Java from a practical perspective, as well as the use of various cases and avoid the pit guide, welcome to follow me.

♨ The essay question ♨

Finished reading may not understand, understand may not be. Here, the last three questions to help you review:

  1. Is China in the northern or southern hemisphere? Eastern or Western hemisphere?
  2. What are the differences and connections between GMT and UTC?
  3. Does China have daylight saving time?

☀ Recommend reading ☀

  • .
  • Use MessageFormat#format for string concatenation
  • 8. Formatter unification — Spring’s Formatter abstraction
  • 9. The details are in the book. The Formatter registry is a neat design
  • .

♚ statement ♚

This article belongs to the column: Java advanced, public number background reply column name can get all the content.

Share, grow, refuse to hide. Pay attention to [BAT utopia], reply keyword column has Spring technology stack, middleware and other small and beautiful original columns for free learning. This article has been included in www.yourbatman.cn.

This article is A brother (YourBatman original article, without the permission of the author/open white shall not be reproduced, thank you for your cooperation.