In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly talks about "what are the ways to deal with Ruby date conversion". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the processing methods of Ruby date conversion"!
The three classes Date, Time, and DateTime in Ruby provide date-time-related operations.
Date can only handle dates
Time can handle date and time
DateTime can also handle dates and times
Among them, DateTime is a subclass of Date, which is a supplement to the time data. To use the Date and DateTime classes, simply import the date library, and to use the Time class, import the time library.
Require 'date' # provides Date and DateTime classes require' time' # provides Time classes (can be used directly, but there are more methods after import)
In general, common operations for operating date and time include:
Create (build) date and time object
Convert between string and date-time object
Comparison of date and time
Operation of date and time
Operating time zone
Wait...
Each of these three classes provides some methods, many of which overlap. According to my personal test, DateTime is the most efficient standard library.
Below, these three classes are introduced together for a variety of common functions.
Ruby build date time object
All three classes can directly construct date and time objects. Where Date can only construct dates, not time objects.
Date construct date object
Date constructs a date object. If the time part is provided, the time part is ignored. Because there is no time part involved, it is not possible or necessary to specify a time zone.
Ruby
# 1. Construct the current date object: Date.today > > Date.today= > # > > puts Date.today2019-08-0802. Construction specified date: Date.new## can construct a date beyond 2038 # # if no month and day are given, the default is 1 month # if no parameters are provided, the default is-4712 January 1, which makes no sense # # if you give a part of time, then report an error > > Date.new (2018 Date.new) > # > Date.new (2078) = > # > Date.new (1900) = > # > Date.new= > # # 3. Construct specified date: Date.parse## parses to date format # # if given time part, ignore # # for years, you can give 1, 2, and 4 digits # # for 1, 2 digits, if the value is greater than or equal to 69, the default is 1900 for the value between 0 and 68 Add 2000 > > Date.parse ('2007 Date.parse 09 / 12') = > # > > Date.parse ('2007 / 9 / 12) = > # > > Date.parse (' 2007-9-12') = > # > > Date.parse ('2007-9-12 Date.parse 3059') = > # > > Date.parse ('08-9-12') = > # > > Date.parse ('68-9-12') = > # > > Date.parse ('69-9-12') = > # # 4. Use the strptime method to convert a string in a given format to a date-time object # # for more information about supported formats, see > > Date.strptime ('2001-02-03,'% YMY% mmi% d') = > # > > Date.strptime ('02-03-2001,'% MMI% dmi% Y') = > # Time to construct a date-time object
The common methods are: new (alias now), at, local (alias mktime), parse.
Note: the Time class does not have a strptime method to convert a given format string to a date-time object.
# 1.new () or now () build the current date-time object # # new can also build the date-time object based on the given parameters Unattended time is equivalent to now## can specify time zone > > Time.now= > 2019-08-05 14:12:30 + 0800 > > Time.new= > 2019-08-05 14:12:31 + 0800 > > Time.new (2007 epoch 11-06 17:10:00 + 080 minutes 2.at () convert epoch to date-time object # # support time zone Decimal seconds, milliseconds, microseconds, nanoseconds > > Time.at (1553488199) = > 2019-03-25 12:29:59 + 0800 > > Time.at (1553488199, in:'+ 08 in') # specified time zone = > 2019-03-25 12:29:59 + 0800 > > Time.at (1553488199.3). Usec # decimal seconds 0.3 seconds That is, 3 millisecond = > 299999 > > Time.at (1553488199123.345 millisecond). Usec # millisecond parameter = > 123344 > > Time.at (1553488199123.345). Nsec # microsecond parameter = > 123344 > Time.at (1553488199123.345 magnified usec). Nsec # microsecond parameter = > 123344 > > Time.at (15534881993flyer Nsec). Nsec # nanosecond parameter = > 1233.mktime or local to build the date and time object of the local time zone based on the parameter # Using gm () or alias methods utc () # # mktime/local and gm/utc, other equivalents except time zone > > Time.mktime (2009-10-23 14:03:06 + 0800 > > Time.mktime (2009-10-23 00:00:00 + 0800 > > Time.mktime (2009-10-01 00:00:00 + 080 calendar 4.parse converts a date-time object based on a string) You can also specify a time zone > > Time.parse ("12:29:59 on 2009-12-25") = > 2009-12-25 12:29:59 + 0800 > > Time.parse ("2009-12-25") = > 2009-12-25 00:00:00 + 0800 > > Time.parse ("2009 Compact 12") = > 2009-12-01 00:00:00 + 0800 > > Time.parse ("12:29:59 on 2009-12-25 + 00:00") # specified time zone = > 2009-12-25 12:29 : 59 + 0000 > > Time.parse ('2009-07-12 16 32 40.00123') .nsec # specify fractional seconds = > 1230000
Since the time zone of the date-time object constructed by the Time class methods described above defaults to + 08:00 (East eighth Zone, China's time zone is East eighth), it is optional to specify a time zone.
But the default time zone for the following methods of the DateTime class to construct a date-time object is + 00:00, so you usually specify a time zone.
DateTime constructs date-time objects
DateTime is a subset of Date, and because some methods are overridden, some method parameters are slightly different. The most commonly used constructors are new, now, parse, and strptime.
In addition, the DateTime object contains nanoseconds.
# 1.new () method to construct a DateTime object # # you can specify a time zone and a fractional second > > DateTime.new (2009 meme 1, 2, 3, 4, 4) = > # > DateTime.new (2009, 1, 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, That is, millisecond = > # > > DateTime.new (2009, 1, 2, 3, 4, 5.3 Sec_fraction= > (3 sec_fraction= 10) # 2.now () get the current time: > > DateTime.now= > # # 3.parse parses the string as a date-time object > > DateTime.parse ('2009-12-20 12 DateTime.now=-20 12:03:30 + 8') = > # > DateTime.parse ('2009-12-20 12:03:30 + 8') = > # # parses a string of a given format as a date-time object # # about supported formats Refer to the following > > DateTime.strptime ('2009-12-20 12:03:30 + 8 million minutes% YMY% MMI% d% H:%M:%S% z') = > #, time validity Test
When building a date-time object, some dates and times are invalid, but it is troublesome to deal with them because of the different range of values and the different values of special dates and special time points.
For example, there may be 29, 30, 31 days a month, but November 31 is invalid. For example, the number of seconds ranges from 0 to 60, but the 61st second is valid only as a leap second, so the 61st second at almost all times is the wrong number of seconds.
Time can detect invalid time out of range, but cannot detect invalid time within range. For example, Time knows that November 31st is wrong, but it does not know that November 31st is wrong. In fact, Time will carry parts that are out of the valid range, such as November 31st to December 1st.
# effective date > > Time.new (2007 pencils 11-30, 17-10) = > invalid dates within the range of 2007-11-30 17:10:30 + 080 minutes, carry to December 1 > Time.new (2007-11-01 17:10:30 + 080 seconds) = > 2007-12-01 17:10:30 + 080 seconds > Time.new (2007-12-01 17:10:59 + 080 minutes 61 seconds to the next minute > Time.new (2007-12-01 11 mins 31gamma 10minute 60) = > 2007-12-01 17:11:00 + 080 seconds error seconds Report an error > > Time.new (2007 pry 11, 31, 17, 10) ArgumentError: sec out of rangefrom (pry): 25:in `date of initialize'# error, report error > > Time.new (2007 11, 31, 17, 10, 59) ArgumentError: argument out of rangefrom (pry): 26:in `initialize'
The carry-around feature of Time is sometimes beneficial, but not good for detection. Fortunately, Date and DateTime can well detect invalid dates and times. As long as they are invalid dates and times, they all report errors. Date can only detect invalid dates, DateTime can detect invalid dates, and invalid times can also be detected.
# Date detection invalid date > > Date.new (2007 31:in 11 new' 30) ArgumentError: invalid datefrom (pry): 28:in `initialize'# DateTime test invalid date and time > DateTime.new (2007 31:in 11 new' 13) ArgumentError: invalid datefrom (pry): 31:in `pint > > DateTime.new (2007 Mei 11 mine30) ArgumentError: invalid datefrom (pry): 32:in `new'
Since they report errors, you only need to add the exception catch code to complete the date-time validity test. For example, use the DateTime class in the Time class to detect a valid date and time:
Class Time def self.valid? type conversion between rescue returin nil end dt endendate, Time and DateTime objects of rescue returin nil end dt endendate, Time and DateTime objects
The origin of these three categories:
The Time class is an encapsulation of the time function of the underlying C library, which is usually based on UNIX epoch, so it cannot represent the time before 1970
The Date class is a supplement to the Time class, which is used to handle times before 1970, but it can only handle dates, not times
DateTime inherits from Date and can handle date and time at any point in time, but some Time features DateTime do not
So there are times when it is necessary to convert them.
Each of these three classes provides the following three methods to convert between them:
To_dateto_timeto_datetime
For example:
# Date object conversion > > Date.today.to_date= > # > > Date.today.to_time= > 2019-08-05 00:00:00 + 0800 > > Date.today.to_datetime= > # # Time object conversion > > Time.now.to_date > > Time.now.to_time > > Time.now.to_datetime# DateTime object conversion > > DateTime.now.to_date > > DateTime.now.to_time > > DateTime.now.to_datetime
It should be noted that the date class object does not have a time zone because it does not contain a time section. So:
Time and time zone data will be lost when Time/DateTime is converted to Date.
The Date object to_time is converted to a Time object, and the time zone is set to its default time zone "+ 08:00", while to_datetime is converted to a DateTime object, and its default time zone is set to "+ 00:00". But the conversion between Time and DateTime does not change the time zone
D = Date.new (2019 d.to_time 23) d.to_time # = > 2019-05-23 00 0800d.to_datetime.to_s # = > "2019-05-23T00:00:00+00:00" date time and conversion between strings and numeric values
This is a common requirement.
Date time to string:
Convert to_s to a specific string format
Strftime is converted to a custom string format, see below
Date time to numeric value: can be converted to numeric value only if the time part is included (that is, Date is not discussed)
Usually converted to epoch time, which supports integers, floating-point numbers, and fractions
String to date time: the previous construction date time object section has been introduced
Numerical value to date time: the previous construction date time object section has been introduced
Date-time objects also support conversion to arrays.
First look at the Time type object, which supports to_s, to_f, to_i, to_r (transfer score), and to_a (transfer array).
# turn string > > Time.now.to_s= > "2019-08-05 15:29:49 + 0800" # turn value, that is, integer epoch, which is the opposite function of Time.at > > Time.now.to_i= > 156499019 turn floating point number, that is, decimal epoch## retains 6 decimal places by default, that is, microsecond level # # can be formatted and retained as nanosecond string # # but cannot be converted to nanosecond level floating point number Because it is out of the range of float precision # # you can use BigDecimal to save floating-point numbers as scientific notation > > Time.now.to_f= > 1564990197.671165 # microseconds > > ".9f"% Time.now.to_f= > "1564990502.569714785" # nanosecond string > > (".9f"% Time.now.to_f). To_f= > 1564991500.1034229 # exceeded Cut # # Save decimal scientific notation floating point using BigDecimal > > require 'bigdecimal' > > BigDecimal ("% .9f"% Time.now.to_f) # nanosecond floating point = > 0.1564991123879058599e10# transfer > > Time.now.to_r= > (3912475500217301max 2500000) # rotation array # # 10 array elements # [sec,min,hour,day,month,year,wday,yday,isdst Zone] # [seconds / minutes / day / month / year / midweek / daylight saving time / time zone] > > Time.now.to_a= > [4,30,15,5,8, 2019, 1217, false, "DST"]
Notice that the time zone viewed by Time is displayed as DST, CST, UTC, GMT, while the time zone viewed by DateTime is displayed in a manner similar to "+ 08:00".
And watch Date and DateTime convert these types. In fact, Date/DateTime supports very few transformation methods, they only support to_s, other methods do not support. So, if you want to convert to an integer, you can first to_time, and then to_i.
> > Date.today.to_s= > "2019-08-05" > > Date.today.to_time= > 2019-08-05 00:00:00 + 0800 > > Date.today.to_time.to_i= > 1564934400 > > DateTime.now.to_s= > "2019-08-05T15:55:05+08:00" > > DateTime.now.to_time.to_f= > 1564991712.1981702strftime method
Strptime converts (parses) a string in a given format to a date-time object, while strftime converts a date-time to a string in a given format.
The three classes Date, Time, and DateTime all have strftime.
> > d = Date.today > > d.strftime ("% Y-%m-%d% H:%M:%S") = > "2019-08-05 00:00:00" > dt = DateTime.now > > dt.strftime ("% Y-%m-%d% H:%M:%S") = > "2019-08-05 16:00:03" > > t = Time.now > > t.strftime ("% Y-%m-%d% H:%M:%S") = > "2019-08-05 16:01:07"
Where the percent sign is the formatted string placeholder in the date time.
In addition, the format used by strftime and strptime is uniform. The following is excerpted from the official manual: strftime
% Flags:- don't pad a numerical output._ use spaces for padding.0 use zeros for padding. ^ upcase the result string.# change case.The minimum field width specifies the minimum width.The modifiers are "E", "O", ":", ":" and ":". "E" and "O" are ignored. No effect to result currently.Format directives:Date (Year, Month, Day):% Y-4-digit integer years, can be negative% C-year / 100 (round down. 20 in 2009)% y-year% 100m-double digit month Fill in 0 (01.. 12)% m blank-padded (1.. 12)%-m no-padded (1.. 12)% B-English name of month (January)% ^ B full name of month in uppercase (JANUARY)% b-abbreviated month name (Jan)% ^ b capitalized month abbreviation (JAN)% h-equivalent At% b% d-double-digit days of the month Fill 0 (01.. 31)%-d no-padded (1.. 31)% e-mid-month days when insufficient, and (1.. 31)% j-mid-month days filled with blanks 0 fill (001.. 366) Time (Hour, Minute, Second, Subsecond):% H-24-hour clock, zero-padded (00.23)% k-24-hour clock, blank-padded (0.23)% I-12-hour clock, zero-padded (01.. 12)% l-12-hour clock Blank-padded (1.. 12)% P-lowercase (am or pm)% p-uppercase (AM or PM)% M-Minute of the hour (00.59)% S-Second of the minute (00.60)% L-milliseconds (000.999)% N-decimal seconds The default is 9 decimal places, namely nanosecond% 3N millisecond millisecond (3 digits)% 6N microsecond microsecond (6 digits)% 9N nanosecond nanosecond (9 digits) N picosecond picosecond (12 digits) N femtosecond (15 digits) N attosecond (18 digits)% 21N zeptosecond (21 digits)% 24N yoctosecond (24 digits) Time zone:% z-time zone Offset from UTC (for example: + 0900)%: Z-time zone, offset from UTC, but with a colon (+ 09:00)%:: Z-time zone, offset from UTC, but with two colons (+ 09:00:00)%:: Z-time zone, offset from UTC The colon is random (+ 09 Weekday 09 SUNDAY 30)% Z-equivalent to% z (+ 09:00) Z:% A-the full name of the day of the week (Sunday)% ^ A capitalized days of the week (SUNDAY)% a-days of the week abbreviated (Sun)% ^ a capitalized days of the week (SUN)% u-numeric days of the week (1. 7) 1 denotes ISO (Monday is 1,1.. 7)% w-numerical day of the week (0,6), and 0 means ISO 8601 week-based year and week number:The week 1 of YYYY starts with a Monday and includes YYYY-01-04.The days in the year before the first week are in the last week ofthe previous year. % G-The week-based year% g-The last 2 digits of the week-based year (00.99)% V-Week number of the week-based year (01.. 53) Week number:The week 1 of YYYY starts with a Sunday or Monday (according to% Uor% W). The days in the year before the first week are in week 0. % U-Week number of the year. The week starts with Sunday. (00.53)% W-Week number of the year. The week starts with Monday. (00.53) Seconds since the Unix Epoch:% s-epoch seconds That is, the number of seconds since 00:00:00 UTC from 1970-01-01 epochLiteral string:% Q-millisecond epochLiteral string:% n-Newline character (\ n)% t-Tab character (\ t)%-Literal ``% 'characterCombination: where% F and% T commonly used% c-date and time (% a% b% e% T% Y)% D-Date (% m/%d/%y)% F-The ISO 8601 date format ( % Y-%m-%d)% v-VMS date (% e-%b-%Y)% x-Same as% D% X-Same as% T% r-12-hour time (% I:%M:%S% p)% R-24-hour time (% I:%M:%S% M)% T-24-hour time (% H:%M:%S)% +-date (1) (% a% b% e% H:%M:%S% Z) % Y) View date and time information
For example, check the year, month, minutes, seconds, time zone and other information in a date.
For Date and DateTime objects, the following methods are provided to view each part of the information:
Year
Month or mon
Day
Hour
Minute or min
Second or sec
Sec_fraction or second_fraction: view decimal seconds (results are displayed as fractions)
Zone: viewing time zon
Cweek: view the week ordinal of the year (1-53)
Yday: view the mid-year day (the day of the year, 1-366)
Mday: view mid-month days (1-31)
Wday: check out the day of the week (day of the week, 0-6 for Sunday, 6 for Saturday)
Day_fraction: look at the past number of times in a day, expressed in scores. For example, 12:00 at noon represents the past 1max 2. See the example below.
Monday?:, is it Monday?
Tuesday?:, is it Tuesday?
Is wednesday?: Wednesday?
Thursday?:, is it Thursday?
Is friday?: Friday?
Is saturday?: Saturday?
Is sunday?: Sunday?
Is leap?: a leap year?
For the Time object, in addition to the above methods (but does not support sec_fraction/second_fraction), it also supports directly viewing milliseconds, subtleties, nanoseconds, that is, converting fractional seconds to corresponding unit values:
Subsec: equivalent to sec_fraction/second_fraction, that is, returns fractional seconds as fractions
Usec: milliseconds
Nsec: nanosecond
# DateTime > > dt = DateTime.new (2009 focus 7 > dt.year # = > 2009 > > dt.mon # = > 7 > > dt.day # = > 12 > > dt.mday # = > 12 > > dt.cweek # = > 28 > > dt.hour # = > 16 > > dt.min # = > 32 > > dt.sec # = > 40 > > dt.sec_fraction # = > (123max 100000) > > dt.yday # = > 193 > > dt.wday # = > 0Sunday > > dt.sunday? # = > true# DateTime: day_fraction > > DateTime.new 12). Day_fraction= > (0pact 1) > > DateTime.new. Day_fraction= > (1hamp2) > > DateTime.new (2009Yue7 12pr 16pr 32pr 40). Day_fraction= > (1489Maq2160) > > DateTime.new (2009pr 712Eng 232959). Day_fraction= > (86399Band 86400) > DateTime.new (2009Power7) Day_fraction= > (5956000123Universe 8640000000) # Time > > t = Time.parse ('2009-07-12 16purr 32 Time.parse 40.00123') > > t.year # = > 2009 > > t.subsec # = > (123top 100000) > > t.usec # = > 1230 > > t.nsec # = > 1230000 date and time operation
This is a more common requirement, such as the date after 7 days, the date 10 days ago, and so on. However, for Ruby, these are very simple, because it has implemented the relevant addition and subtraction operators and some related methods, which is very convenient.
Date-time addition and subtraction operation
Date/DateTime/Time all implement +-operations, and they all return new date-time objects:
For Time, it is used to increase and decrease seconds respectively (can be decimal)
For Date/DateTime, it is used to increase and decrease the number of days respectively (can be decimal)
The following is an example of an Date/DateTime class object that uses addition and subtraction to perform date operations:
> > d = Date.parse ('2019-02-26') > > dt = DateTime.parse > > d + 1 = > # > > d + 3 = > # > > d + 3 = > # > (dt + 3). To_s= > "2019-03-01T12:30:30+00:00" > > (dt + 2.5). To_s= > "2019-03-01T00:30:30+00:00"
The following is an example of an Time class object using addition and subtraction for time operations. Note that the second operation can be a decimal:
> t = Time.new = 2019-02-26 12:30:30 + 0800 > t + 20 # = > 2019-02-26 12:30:50 + 0800 > > t + 86400 # = > 2019-02-27 12:30:30 + 0800 > > t + 86400 * 3 # = > 2019-03-01 12:30:30 + 0800 > > (t + 10.32). Nsec # = > 320000000 month operation
For the Date/DateTime class, it also provides the function of month operation >:
For the next few months, you can give a negative number to represent the first few months.
> dt.to_s # February 26 = > "2019-02-26T12:30:30+00:00" > > (dt "2019-01-26T12:30:30+00:00" > (dt > >-1). To_s= > "2019-01-26T12:30:30+00:00" > > (dt "2019-03-26T12:30:30+00:00" > > (dt > > 1). To_s= > "2019-03-26T12:30:30+00:00"
However, it should be noted that the last day of some months is different, for example, the last day of March is 31, the last month forward is February, and the last day of February may be 28 or 29. For the month operation, when the number of days of the month after the operation exceeds the range of the month, the last day of the month will be automatically taken.
> > d = Date.new (2019-02-28) > > (2019-02-28)
This may lead to some unexpected results. For example, moving forward two months on March 31 would have been January 31, but by moving forward one month twice, the result would be January 28 or January 29.
> > d = Date.new (2019-01-31) > > (d > (d) it is not safe to do the month operation. If you want to be safe, you should try to use the addition and subtraction of date and time.
Prev and next of date and time
In addition to the +-> operators, some operations such as next/prev are also supported for Date/DateTime:
Next or succ
Next_day
Next_month
Next_year
Prev_day
Prev_month
Prev_year
Of course, all of these can be equivalent through the +-> introduced earlier. Moreover, there are also unsafe problems with the operation of month and year, as described in face > above.
Comparison of date and time
Date/Time/DateTime implements operators, and they all mix-in Comparable, so you can compare sizes directly, or you can use between? This is a way to determine whether a point in time is within the time range. This is a very practical and convenient function.
In addition, Date implements the = = operator, which is equivalent to = =, so it returns true as long as the date is the same, and DateTime is a subclass of Date, so it also applies to DateTime objects, although their time portions may be different. Therefore, Date and DateTime objects can be compared to each other, but neither of them can be compared directly to Time objects.
> > D1 = Date.new (2019pr 5je 23) > D2 = Date.new (2019pr 5je 24) > d1
< d2 #=>True > > dt1 = DateTime.new (2019 DateTime.new 5, 23, 12, 30) > dt2 = DateTime.new (2019, 5, 23, 23, 12, 12, 30, 30, 30, 34) > > dt1
< dt2 #=>True > > dt1 = dt2 # = > true, although the time is different, the result true > > D1 = dt1 # = > true > > T1 = Time.new
< t2 #=>Iteration of true date and time
Date/DateTime also supports both downto and upto date iterations (not supported by Time), with a default of one day per iteration.
In addition, step iterations are supported, which can specify the step size of the iteration.
> > d.to_s # = > "2019-03-31" > > (dumb7). To_s # = > "2019-04-07" > > d.upto (dumb7) {| date | puts date} 2019-03-312019-04-012019-04-022019-04-032019-042019-042019-042019-062019-04-07 > (dumb7) .downto (d) {| date | puts date} 2019-04-072019-042019-062019-042019-042019-042019-042014-042019-042019-042014-042019-042019-042014-042019 032019-04-022019-04-012019-03-31
For step:
Step (limit [, step=1]) → enumeratorstep (limit [, step=1]) {| date |...} → self
The only thing to note is that the step statement block returns the original object, so you should do something meaningful in the statement block and do not rely on the statement block to build the return value.
The simple usage is as follows:
D = Date.new (2019, 5,23) D1 = Date.new (2019, 5,28) d.step (D1) {| date | puts date} puts "-" * 20d.step (D1, 2) {| date | puts date}
Output result:
2019-05-232019-05-242019-05-252019-05-262019-05-272019-05-28-2019-05-232019-05-252019-05-27 efficiency comparison of several build date-time objects
Date/DateTime/Time classes all have several ways to build date-time objects, but the performance of different build methods must be different.
Let's test these ways to build 100W date-time objects to compare their performance.
The conclusion is explained here:
Based on the test results, using the new method to build date-time objects is almost always the best choice.
Manual time zone assignment is less efficient than automatic time zone setting, with the exception of Time.new, where Time.new is several times more efficient after specifying time zone
The parse method is the least efficient, and much worse.
Several Construction methods of Date Class
Date can only build date objects and does not contain time, so it is not appropriate in some scenarios.
The following is a comparison of the efficiency of several ways to build 100W date objects. As you can see from the results, Date.new is the most efficient and Date.parse is the worst.
# # Date.new$ time ruby-ritual date'- e '1000000.times {| x | Date.new (2017-3-23)}' real 0m0.410suser 0m0.203ssys 0m0.203s## Date.parse$ time ruby-ritual date'- e '1000000.times {| x | Date.parse ("2017-3-23")}' real 0m2.604suser 0m2.406ssys 0m0.219s## Date.strptime$ time ruby-ritual date'- e '1000000.times {| x | Date.strptime ("2017-3-23") Several construction methods of "% Y-%m-%d")} 'real 0m0.790suser 0m0.609ssys 0m0.203sTime class
Efficiency comparison of several ways for Time class to build 100W date-time objects. As can be seen from the results:
Time.at is the most efficient to build, but it can only convert epoch timestamps
Among other common construction methods, Time.new is the most efficient, especially when the time zone is specified manually, it is almost comparable to Time.at.
Time.parse efficiency is the worst, and much worse.
# Time class # # Time.new, does not specify a time zone $time ruby-ringing time'-e '1000000.times {| x | Time.new (2017Leijin3 Time.new 23jing16pjong15)}' real 0m2.546suser 0m0.969ssys 0m1.578s## Time.new, and specifies a time zone $time ruby-rattletime'-e' 1000000.times {| x | Time.new (2017jing3 mine23, 16))} 'real 0m0.663suser 0m0.453ssys 0m0.219s## Time.at Do not specify the time zone $time ruby-e '1000000.times {| x | Time.at (1490257815)}' real 0m0.358suser 0m0.141ssys 0m0.219s## Time.at, specify the time zone $time ruby-e '1000000.times {| x | Time.at (1490257815 in: "+ 08:00")}' real 0m0.941suser 0m0.734ssys 0m0.219s## Time.parse Specify time zone $time ruby-ringing time'-e '1000000.times {| x | Time.parse ("2017-03-23 16:30:15 + 0800")}' real 0m10.949suser 0m10.422ssys 0m0.531s## Time.parse, not specify time zone $time ruby-ringing time'-e '1000000.times {| x | Time.parse ("2017-03-23 16:30:15")}' real 0m10.972suser 0m8.953ssys 0m1.984s## Time.mktime Specify the time zone $time ruby-ringing time'-e '1000000.times {| x | Time.mktime (2017 time ruby 3Power15, "+ 08:00")}' real 0m2.575suser 0m0.984ssys 0m1.578s## Time.mktime, and do not specify the time zone $time ruby-ringing time'-e '1000000.times {| x | Time.mktime (2017 L3 Magi 23 heroine 161,30)}' real 0m2.490suser 0m0.984ssys 0m1.531sDateTime class construction methods
Efficiency comparison of several ways for DateTime class to build 100W date-time objects. As can be seen from the results:
The construction efficiency of DateTime.new is the best, and it makes almost no difference whether you specify a time zone or not.
DateTime.parse efficiency is the worst, and much worse.
# # DateTime.new: do not specify a time zone $time ruby-rpm date'- e '1000000.times {| x | DateTime.new (2017Leijin3 Magi 23je 1630jue 15)}' real 0m0.409suser 0m0.219ssys 0m0.203s## DateTime.new: specify a time zone $time ruby-ringing date'- e '1000000.times {| x | DateTime.new (2017L3 Magi 23dinger 161,30515) "+ 08:00")} 'real 0m0.502suser 0m0.328ssys 0m0.188s## DateTime.strptime: no time zone specified $time ruby-ritual date'-e '1000000.times {| x | DateTime.strptime ("2017-3-23 16:30:15" "% Y-%m-%d% H:%M:%S")} 'real 0m0.994suser 0m0.797ssys 0m0.219s## DateTime.strptime: specify the time zone $time ruby-ritual date'-e '1000000.times {| x | DateTime.strptime ("2017-3-23 16:30:15 + 08:00" "% Y-%m-%d% H:%M:%S% z")} 'real 0m1.838suser 0m1.656ssys 0m0.203s## DateTime.parse: do not specify the time zone $time ruby-rdatedate'-e' 1000000.times {| x | DateTime.parse ("2017-3-23 16:30:15")}' real 0m6.206suser 0m5.984ssys 0m0.203s## DateTime.parse: specify the time zone $time ruby-rdatedate'-e' 1000000.times {| x | DateTime.parse ("2017-3-23 16:30:15 + 08:00")} 'real 0m6.944suser 0m6.734ssys 0m0.203s so far I believe that you have a deeper understanding of "what are the processing methods of Ruby date conversion?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.