How to understand strptime vs. strftime

前端 未结 3 1906
夕颜
夕颜 2021-01-31 02:11

What\'s the difference between strptime and strftime? I see that strptime is a method in the DateTime class, and strfti

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 02:48

    The difference between Time and DateTime has to do with implementation. A large amount of the DateTime functionality comes from the Rails world and is an arbitrary date with time of day. It's more of a calendar-based system. Time is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.

    In short, DateTime is what you get from a database in Rails where Time is what Ruby has traditionally used. If you're working with values where dates are important and you want to know things like the end of the month or what day it'll be six weeks ahead, use DateTime. If you're just measuring elapsed time and don't care about that, use Time. They're easy to convert between if necessary.

    Date on the other hand is just a calendar date and doesn't have any associated times. You might want to use these where times are irrelevant.

    strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification. I've rarely seen strptime used since DateTime.parse is usually good at picking up on what's going on, but if you really need to spell it out, by all means use the legacy parser.

提交回复
热议问题