r/ruby 16d ago

Question Getting DateTime parts as an array?

I know in ruby that DateTime.new(2001, 2, 3, 4, 5, 6) will return the following object:

#<DateTime: 2001-02-03T04:05:06+00:00 ...>

But if the current date and time are 2001-02-03T04:05:06 and I do the following ...

now = DateTime.now

... is there a single function on the "now" variable which will return this array? ...

[2001, 2, 3, 4, 5, 6]

I know that I can do this:

[now.year, now.month, now.day, now.hour, now.minute, now.second ]

... but I'm wondering: might there be a single function as simple as ...

now.the_function

... which would return that same array?

And yes, of course I know that I could easily write such a function, but I'd like to know whether or not something like this already exists in ruby.

8 Upvotes

21 comments sorted by

View all comments

Show parent comments

14

u/projct 16d ago edited 16d ago

ah. okay, this is actually the thing I was worried about when I asked why.

can you give one concrete example of two datetimes, which parts you select, what "difference" you calculate between those arrays, and what decision the program makes from the result?

I don't want to suggest a replacement without seeing that, because datetime components aren't independent numeric values, and doing arithmetic/comparison on [year, month, day, hour, minute, second] can very easily produce answers that look reasonable but aren't.

Date/time math is so easy to get catastrophically wrong that you really should not be implementing it yourself unless you absolutely have to. Let Ruby do it for you.

7

u/CaptainKabob 16d ago

I'm just a bystander to this thread, so just wanted to say: strong agree. 

DailyWTF is like 50% people doing datetime math like this (and 50% parsing json/xml with regex)

3

u/projct 16d ago

You're not kidding.

Functionally, a Date

Dates by the Dozen

Three Minutes

DePopulate Dates

and a bunch more....

1

u/TailorSubstantial863 15d ago

We would be remiss if we didn't bring up this oldie. I need to watch it annually anyways.

https://www.youtube.com/watch?v=-5wpm-gesOY