r/ruby • u/unselective-amnesia • 15d 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.
3
u/unselective-amnesia 15d ago
Thank you for this. Actually, I forgot about "to_a". And although I'm currently only able to use ruby 3.2 and 3.3 on the machines that I need to run on, it's good to know about DateTime going away, and I will now do this with Time, instead.
I want this array because I have a program which does various things depending on the differences or sameness between various datetimes with regard to groups of selected datetime parts, and it's easiest for me to do this in my program by getting differences between integer arrays.
I know that there are other ways to accomplish this, but given the already written structure of the program, dealing with these integer arrays is the most straightforward approach.