Erlang Date and time processing

Source: Internet
Author: User
Tags date1 deprecated time zones iso 8601 local time

In the development process, there are two concepts related to the regional area: character encoding and time; the evolution of the Code and Time specification has a historical legacy, and it is a corner of the development of software. About character encoding I've worked on a post before, [Erlang 0024] Erlang binary Data processing this part of the knowledge is very interesting, in particular, Gulliver's travels led to the small end of the concept, fun; In peacetime notes also fragmented recorded some and time processing related content, today retrace the relevant information compiled in this.

First explain the concept of time-related: The concept of time GMT TimeGMT (Greenwich Mean Time, GMT) refers to the standard time of the Royal Greenwich Observatory in the suburbs of London, UK. Because the Prime meridian is defined through the meridians there. Since February 5, 1924, the Greenwich Observatory has been distributing information to the world on an hourly interval.
In theory, the midday of Greenwich Mean time is the time when the Sun crosses the Greenwich Meridian. Due to the uneven movement of the Earth in its elliptical orbit, this moment may have an error with the actual sun, with a maximum error of up to 16 minutes. Because the Earth's daily rotation is somewhat irregular and slowly slowing down, As a result, Greenwich Mean time is no longer used as standard. The standard time now is Coordinated Universal Time (UTC), which is made by atomic clocks. UTC TimeThe UTC time is the abbreviation of Universal, coordinated, or the world standard Time or the coordinated time of the world when the Chinese name is coordinated world; This slightly strange name comes from this:  The International Telecommunication Union wants to reconcile the world with a single abbreviation in all languages. English and French-speaking people also want their respective language abbreviations, cut and TUC, to be able to become international standards. The result was a compromise using UTC.   This time system is used in many Internet and world Wide Web standards, for example, Network Time protocol is a way to coordinate the world when used in the Internet. In military and aviation, coordinated world time zones are expressed using "Z". In mainland China, Hong Kong, Macao and Taiwan's local time is 8 hours faster than UTC, will write utc+8, commonly known as East 8 District。 If the local time is slower than UTC time, such as Hawaii time is 10 hours slower than UTC time, will write UTC-10, and commonly known as the West 10 district.

Time Zone
The theoretical time zone is centered on a meridian that is divisible by 15, extending 7.5 degrees to the east and the West, i.e. dividing a time zone every 15 °, which is the theoretical time zone. When the time zone of the theory uses its central meridian (or Standard Meridian). So each time zone, the area of one hours, the difference between the time zone, How many hours is the difference? The Eastern time zone is earlier than the West Zone. In order to avoid the disorder of the date, the concept of International Date line is proposed. In order to avoid the national boundaries, some time zones are irregular in shape, and the national administrative dividing line is the time zone for the larger countries, which is the actual time zone, that is, the legal time zone. All time zones are set relative to UTC. Unix time StampUnix time or POSIX time is the time representation used by UNIX or Unix-like systems: The total number of seconds from January 1, 1970 0:0 0 seconds from UTC. 2038 issue: Most Unix-based systems are now 32-bit, meaning they represent time in 32-bit binary digits. But they can only be represented at a coordinated world time. January 19, 2038 3:14 07 seconds (binary: 01111111 11111111 11111111 11111111), the next second binary number will be 10000000 00000000 00000000 00000000, which is negative, As a result, the system will misinterpret the time as December 13, 1901 20:45 52 seconds (also say return to 1970). This may cause problems with the software, causing the system to become paralyzed. The current solution is to convert the system from 32-bit to 64-bit system.  Under 64-bit systems, this time can be represented up to 292,277,026,596 December 4 15:30 08 seconds. Think of a long time ago the millennium bug problem? Gregorian calendar Gregorian calendarThe Gregorian calendar is now the International Universal Calendar, also known as Griel, the Gregorian calendar. The Gregorian calendar "aka" Solar Calendar ", the earth around the sun for one year, for the western countries are universal, it is also known as" Western Calendar. "The Gregorian calendar defines the month, leap months and other methods of calculation; it is a great progress in culture to abolish the Dili dating method. In addition to the Dili years, China also has Ganzhi dating method, this is very interesting, that the 10 days dry    C, Ding, E, self, Geng, Xin, Ren, GUI) and 12 earthly branches (son, ugly, Yin, Mao, Chen, have, noon, not, Shen, unitary, Xu, Hai) are combined together, a total of 60 groups, used to denote the order of the month and day, the cycle, the use of recycling. 2012 is the year, hehe, understand why a lot of people choose to have children this year? Daylight Saving Time DST

In the movie "National Treasure" there is a plot is three people see the dollar behind the 4:10 thought too late, but realized that after the summer season, found that there is still one hours of time, everything is still too late; Daylight saving time (daylight saving time:dst), also known as "Daylight Saver" and "Daylight Saving Time", is a system for saving energy and for people to set local times, which is called "Daylight Saving Time" during the implementation of this system. Usually early in the morning of dawn in the summer for an hour ahead of time, can make people early to sleep, reduce the amount of lighting, to make full use of light resources, thereby saving lighting electricity. The specific provisions of each country adopting daylight savings are different. At present, nearly 110 countries around the world have to implement daylight saving time every year.    Since March 27, 2011, Russia has been permanently using daylight saving time, which has been set aside for an hour and no longer recalled. It was said that the earliest daylight saving time was conceived by Benjamin Franklin, a figure on the $100 bill, when he was the American ambassador to France, when he was accustomed to the early morning sleep of the American rural aristocracy, and saw the Frenchman wake up 10 o'clock on a walk. The night life is too late. So he wrote a letter to the editor of Paris magazine in 1784, saying that the French lifestyle wasted a good sun, suggesting that they go to bed early and get up earlier, saying they can save 64 million pounds of candles a year. But he didn't suggest daylight saving time. It's only suggested that people should go to bed early and get up early. Until 1907, a British architect, William Willett, formally presented the William Villette to the British Parliament, mainly to save energy and provide more time to train soldiers,   But the parliament was not adopted by the debate. Because of his reputation as Benjamin Franklin, many people have ignored Benjamin Franklin as the inventor of daylight saving time and William Villette. China introduced daylight saving time in 1986-1991 and the reason for the stop is: 1. There is no need to implement 2 of the vast majority of the region. Most of China's civilians are accustomed to Beijing, and it's hard for them to accept that daylight savings is superfluous. 3. Daylight saving times make it possible for railways and flights to be revised every year. Cause trouble and inconvenience. AD eraThe "Gregorian era" is an international system of years. The year of birth of the legendary Jesus Christ was born in the Christian Sixth century, when, in order to enlarge the ruling power of the church, priests Emily just everything in Christianity. DateTime format RepresentationCultural differences in the way the date is expressed in different ways, in English, the Commonwealth countries and the United States on the date to express the customary usage of different; to be fluent in communication, there is a date-time specification, ISO 8601 gives a detailed description of the date-time representation, and you can look at the Wikipedia introduction. After the Erlang calendar has learned about this, we return to the technology and look at the calculation of the time in Erlang, which is basically focused on the Calendar module. Usually we call the Erlang:now () obtained from 00:00 GMT, January 1, 1970 elapsed time, the result is composed of: {megasecs, Secs, microsecs}, For the beginning of the Gregorian timing, Erlang goes back to 0. If the time difference is calculated, it needs to be converted into world time before the calculation is performed; the temporal operation is based on the following rules:

Erlang:now () Returns the tuple {megasecs, Secs, microsecs} which is the elapsed time since 00:00 GMT, January 1, 1970 (Zero Hour) on th e assumption the underlying OS supports this. Otherwise, some, and other at time is chosen. It is also guaranteed, subsequent calls to this BIF returns continuously increasing values. Hence, the return value from now () can being used to generate unique time-stamps, and if it's called in a tight loop on a FA St Machine the time of the node can become skewed.

It can used to check the local time of day if the Time-zone info of the underlying operating system is properly co Nfigured.

there is 86400 seconds in a day
there is 365 days in a ordinary year
There is 366 days in a leap year
There is 1461 days in a 4 year period
there is 36524 days in a the year period
there is 146097 days in a the year period
there was 719528 days between Jan 1, 0 and Jan 1, 1970. As well as leap year rules: y is divisible by 4; Or
y is divisible by 400. Modules deprecated or deprecated in the Calendar module: local_time_to_universal_time ({Date1, Time1}), {Date2, time2}time_difference (T1, T2)- > {days, time} common code Erlang:now to local time15> Calendar:now_to_local_time (Erlang:now ()).
{{2012,5,17},{14,32,6}} Erlang:now Turn World Time16> Calendar:now_to_universal_time (Erlang:now ()).
{{2012,5,17},{6,33,2}}
17> Verify the date that is valid20> calendar:valid_date ({0,0,0}).
False
21> calendar:valid_date ({0,1,0}).
False
22> calendar:valid_date ({0,1,1}).
True26> calendar:valid_date (90,1,10).
True get local time, month, day, hour , minute1> {{year,month,day},{hour,min,second}}=calendar:local_time ().
{{2012,5,17},{14,13,14}}
2> B ().
Day = 17
Hour = 14
Min = 13
Month = 5
Second = 14
Year = 2012
Ok Get World Time3> Calendar:universal_time ().
{{2012,5,17},{6,16,27}} local time conversion to world time10> Calendar:local_time_to_universal_time_dst ({{2012,3,12},{3,23,12}}).
[{{2012,3,11},{19,23,12}}]
11> Calendar:local_time_to_universal_time_dst ({{2012,3,12},{4,23,12}}).
[{{2012,3,11},{20,23,12}}]
12> Calendar:local_time_to_universal_time_dst ({{2012,3,12},{5,23,12}}).
[{{2012,3,11},{21,23,12}}]
13> Calendar:local_time_to_universal_time_dst ({{2012,3,12},{15,23,12}}).
[{{2012,3,12},{7,23,12}}]
14> Calendar:local_time_to_universal_time_dst ({{2012,3,12},{16,23,12}}).
[{{2012,3,12},{8,23,12}}] World Time turn local time12> Calendar:universal_time_to_local_time ({{2012,3,12},{3,23,12}}).
{{2012,3,12},{11,23,12}}
13> Calendar:universal_time_to_local_time ({{2012,3,12},{5,23,12}}).
{{2012,3,12},{13,23,12}}
14> Calendar:universal_time_to_local_time ({{2012,3,12},{20,23,12}}).
{{2012,3,13},{4,23,12}} calculate the day of the week13> Calendar:day_of_the_week (1984,5,15).
2
14> Calendar:day_of_the_week (2012,5,17).
4 calculate whether a leap year5> Calendar:is_leap_year (1990).
False
6> Calendar:is_leap_year (2000).
True calculate how many days a certain month is a year7> Calendar:last_day_of_the_month (2000,2).
29
8> Calendar:last_day_of_the_month (2000,3).
31
9> Calendar:last_day_of_the_month (1990,2).
28 seconds to turn time4> Calendar:now_to_datetime (Erlang:now ()).
{{2012,5,17},{5,41,24}}
5> calendar:seconds_to_daystime (87400).
{1,{0,16,40}}
6> calendar:seconds_to_daystime (97400).
{1,{3,3,20}}
7> calendar:seconds_to_daystime (80400).
{0,{22,20,0}} if no more than one day can be used 8> calendar:seconds_to_time (80400).
{22,20,0}
9> calendar:seconds_to_time (86400).
* * Exception error:no function clause matching calendar:seconds_to_time (86400) (Calendar.erl, line 357) time goes to seconds10> calendar:time_to_seconds ({22,20,0}).
80400
11> calendar:time_to_seconds ({1,{22,20,0}}).
* * Exception error:no function clause matching calendar:time_to_seconds ({1,{22,20,0}}) (Calendar.erl, line 390) Computing Unix TimestampTimestamp ()
Calendar:datetime_to_gregorian_seconds (Erlang:universaltime ()). Or: Timestamp ()
{M, S, _} = Erlang:now (),
M * 1000000 + S. Date Time Formatting16> test:now_to_local_string (Erlang:now ()).
"2012-05-17t16:14:42.195510+08:00"
17> test:now_to_utc_string (Erlang:now ()).
"2012-05-17t08:15:26.907466z"
18> Test:timestamp_to_iso (Calendar:local_time ()).
The code below "20120517t16:27:18" implements the time formatting effect above:
Timestamp_to_iso ({{year, Month, day}, {Hour, Minute, Second}}), Lists:flatten (Io_lib:format ("~4..0w~2..0w~2"). .0wt~2..0w:~2..0w:~2..0w ", [Year, Month, Day, Hour, Minute, Second]). now_to_utc_string ({megasecs, Secs, MicroS ECS}) {{year, Month, day}, {Hour, Minute, Second}} = Calendar:now_to_universal_time ({megasecs, Secs, Microsecs }), Lists:flatten (Io_lib:format ("~4..0w-~2..0w-~2..0wt~2..0w:~2..0w:~2..0w.~6..0wz", [Year, Month, day , Hour, Minute, Second, Microsecs]). now_to_local_string ({megasecs, Secs, microsecs}) localtime = Calendar:now_to _local_time ({megasecs, Secs, microsecs}), Utctime = Calendar:now_to_universal_time ({megasecs, Secs, microsecs}), Sec    Onds = Calendar:datetime_to_gregorian_seconds (localtime)-Calendar:datetime_to_gregorian_seconds (UTCTime),                {{H, M, _}, sign} = if Seconds < 0, {calendar:seconds_to_time (-seconds), "-"};    True-            {calendar:seconds_to_time (seconds), "+"} end, {{year, Month, day}, {Hour, Minute, Second}} = LocalTime, Lists:flatten (Io_lib:format ("~4..0w-~2..0w-~2..0wt~2..0w:~2..0w:~2..0w.~6..0w~s~2..0w:~2..0w", [Year, Month, day, Hour, Minute, Second, Microsecs, sign, H, M]).% yyyy-mm-ddthh:mm:ss[.sss]{z|{ +|-}HH:MM}, {megasecs, Secs, Microsecs}datetime_string_to_timestamp (TIMESTR), Case catch Parse_datetime (time    STR) of {' EXIT ', _err}, undefined; TimeStamp, TimeStamp end.parse_datetime (TIMESTR), [Date, Time] = String:tokens (timestr, "T"), D = Parse_date (date), {T, MS, TZH, TZM} = Parse_time (time), S = Calendar:datetime_to_gregorian_seconds ({D, T}), S1    = Calendar:datetime_to_gregorian_seconds ({{1970, 1, 1}, {0, 0, 0}}), seconds = (S-S1)-TZH * 60-TZM * 60,     {Seconds div 1000000, Seconds rem 1000000, ms}.% yyyy-mm-ddparse_date (date), [Y, M, D] = String:tokens (date, "-"),Date1 = {List_to_integer (Y), List_to_integer (M), List_to_integer (D)}, Case calendar:valid_date (Date1) of True    Date1; _, False end.% Hh:mm:ss[.sss]tzdparse_time (time), Case string:str (Time, "Z") of 0, p    Arse_time_with_timezone (time); _, [t | _] = string:tokens (Time, "Z"), {tt, MS} = Parse_time1 (T), {TT, MS, 0, 0} end.parse_ti Me_with_timezone (time), Case string:str (time, "+") of 0, Case string:str (Time, "-") of 0-&G            T        False    _-Parse_time_with_timezone (Time, "-") end; _-Parse_time_with_timezone (Time, "+") End.parse_time_with_timezone (Time, Delim), [T, TZ] = string:        Tokens (time, Delim), {TZH, TZM} = Parse_timezone (TZ), {TT, MS} = parse_time1 (T), Case Delim of "-"    {TT, MS,-tzh,-TZM}; "+" {TT, MS, TZH, TZM} end.parse_timezone (TZ), [H, M] = String:tokenS (TZ, ":"), {[H1, M1], true} = Check_list ([{H, S}, {M, i}]), {H1, m1}.parse_time1 (time), HMS |         T] = String:tokens (Time, "."), MS = Case T of [], 0;  [Val]-List_to_integer (String:left (Val, 6, $)) end, [H, M, S] = String:tokens (HMS, ":"), {[H1, M1,      S1], true} = Check_list ([{H, +}, {M, $}, {S,}]), {{H1, M1, S1}, Ms}.check_list (list), LISTS:MAPFOLDL (          Fun ({L, N}, b)-V = List_to_integer (l), if (v >= 0) and (v =< N), {V, b}; True, {false, false} end end, true, List).

Construct a date string


% a function to format date/time properly (e.g. instead of 9) return_2columns (x), Case    Length (x) of        1            "0" + + X;        _-            X    end.%%% Obviously here can be directly used Io_lib:format ("~2..0b", [X])% returns Date/time as a properly formatted string (e.g. "01-01-2000 12:12:12") get_current_time ()    {{Y, M, D}, {H, Mi, S}} = Calendar:local_time (),    L = Lists:map (fu N (x)                           , X2=integer_to_list (x),                           return_2columns (X2)                   end,                   [Y, M, D, H, Mi, S]                 ),    [Y2, M2, D2, H2, Mi2, S2] = L, Y2 + + + + M2 + + + + D2 + + + H2 + +: + + Mi2 + +    

Of course, the following code snippet is also very likely to be used:

Day (1)-"Mon";d ay (2), "Tue";d ay (3), "Wed";d ay (4), "Thu";d ay (5), "Fri";d ay (6), "Sat";d ay (7)- > "Sun". Month_to_list (1), "  Jan"; month_to_list (2),  "Feb"; month_to_list (3),  "Mar"; Month_to_list (4), "  Apr", Month_to_list (5),  "may", month_to_list (6),  "June"; Month_to_list ( 7), "  Jul"; month_to_list (8),  "Month_to_list"; (9)  

Note: The concept of days (day ) is related to time zones, where time- zone differences are taken into account when using Unix timestamps, such as whether two Unix timestamps are on the same day, timestamps of the start time of a single date, and so on; This issue is especially interesting when you are in the multilingual version of the software

Good night!

Related information:[1] Time zone http://zh.wikipedia.org/wiki/%e6%97%b6%e5%8c%ba[2] National Timing Center network server time release Http://www.time.ac.cn/stime.asp[3] GMT time Http://zh.wikipedia.org/wiki/gmt[4] UTC time http://zh.wikipedia.org/wiki/%E5%8D%94%E8%AA%BF%E4%B8%96%E7%95%8C%E6% 99%82[5] UNIX time http://zh.wikipedia.org/wiki/unix%e6%97%b6%e9%97%b4[6] Millennium bug Problem http://zh.wikipedia.org/wiki/%E5%8D% 83%E5%B9%B4%E8%99%AB[7] Gregorian http://en.wikipedia.org/wiki/gregorian_calendar[8] Daylight saving Time http://zh.wikipedia.org/wiki/%E5 %A4%8F%E6%97%B6%E5%88%B6[9] Date format http://en.wikipedia.org/wiki/iso_8601[10] $ http://zh.wikipedia.org/wiki/100% e7%be%8e%e5%85%83%e7%ba%b8%e5%b8%81

Erlang Date and time processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.