jdog
jdog

Reputation: 10759

Ruby how to get 2018-08-25 from DateTime object?

I have a DateTime property on one of my model objects.

Example data: "2018-08-28T01:00:00.000+00:00"

I am creating a new JSON object based of the DateTime property, but I just want to put this part into it 2018-08-28

I also want to grab the hour part and put it into the JSON object also. For example 01

Currently what I have is this JSON passed over.

{"date":"2018-08-25T18:00:00.000+00:00"}

I want this

{"date":"2018-08-25", "hour":"01"}

Upvotes: 0

Views: 50

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Parse the string into the valid DateTime instance and then print it back in any format you need with DateTime#strftime:

require 'datetime'
DateTime.
  iso8601("2018-08-28T01:00:00.000+00:00").
  strftime('%Y-%m-%d')
#⇒ "2018-08-28"

To get both a date and an hour one might do:

date, hour =
  DateTime.
    iso8601("2018-08-28T01:00:00.000+00:00").
    strftime('%Y-%m-%d,%H').
    split(',')
#⇒ ["2018-08-28", "01"] 

To get a desired hash:

%w|date hour|.
  zip(
    DateTime.
      iso8601("2018-08-28T01:00:00.000+00:00").
      strftime('%Y-%m-%d,%H').
      split(',')
  ).
  to_h
#⇒ {
#    "date" => "2018-08-28",
#    "hour" => "01"
# }

Upvotes: 4

Related Questions