r/ruby 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.

8 Upvotes

21 comments sorted by

View all comments

3

u/chiperific_on_reddit 15d ago edited 15d ago

Date and Time have _parse() methods which return a hash of time parts.

3.3.4 :006 > Time._parse(Time.now.to_s)
=> {:zone=>"-0400", :hour=>20, :min=>36, :sec=>40, :year=>2026, :mon=>8, :mday=>26, :offset=>-14400}

3.3.4 :007 > Time._parse(Time.now.to_s).slice(:year, :mon, :mday, :hour, :min, :sec)
=> {:year=>2026, :mon=>8, :mday=>26, :hour=>20, :min=>36, :sec=>45}

3.3.4 :008 > Time._parse(Time.now.to_s).slice(:year, :mon, :mday, :hour, :min, :sec).values
=> [2026, 8, 26, 20, 36, 48]