What’s the difference between strptime and strftime? I see that strptime is a method in the DateTime class, and strftime is a method in the Time class.
- What’s the difference between
TimeandDateTime, other than that they have different core methods? The explanation for theTimeclass in the Ruby docs is helpful, but the one forDateTimejust says “datetime”. There’s also theDateclass, which says it providesDateandDateTime. Help me make sense of this. - I see
strptimeand I want to pronounce it “strip time”, but that doesn’t make sense. Is there a good mnemonic-device for it? - What do
strptimeandstrftimemean, anyway? - How do you remember which does what?
The difference between
TimeandDateTimehas to do with implementation. A large amount of theDateTimefunctionality comes from the Rails world and is an arbitrary date with time of day. It’s more of a calendar-based system.Timeis 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,
DateTimeis 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.Dateon 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.strptimeis short for “parse time” wherestrftimeis for “formatting time”. That is,strptimeis the opposite ofstrftimethough they use, conveniently, the same formatting specification. I’ve rarely seenstrptimeused sinceDateTime.parseis 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.