Home > Net >  Converting String to Date Without Time?
Converting String to Date Without Time?

Time:01-06

This should be so simple but I'm missing something.

I get an invalid date when trying to convert a string to a Date.

irb(main):076:0> current_date
=> "December 21, 2022 04.00 AM"
irb(main):077:0> current_date.class
=> String
irb(main):078:0> date_format
=> "%M %e, %Y"
irb(main):079:0> date_format_time
=> "%M %e, %Y %l.%i %p"
irb(main):080:0> new_date = Date.strptime(current_date, date_format).iso8601
Traceback (most recent call last):
        2: from (irb):80
        1: from (irb):80:in `strptime'
Date::Error (invalid date)
irb(main):081:0> new_date = Date.strptime(current_date, date_format_time).iso8601
Traceback (most recent call last):
        3: from (irb):80
        2: from (irb):81:in `rescue in irb_binding'
        1: from (irb):81:in `strptime'
Date::Error (invalid date)

I'm trying to convert the date into a string in the format 'YYYY-MM-DD'

Thank you in advance!

CodePudding user response:

Your date_format_time doesn't feel right. Try this instead:

current_date = "December 21, 2022 04.00 AM"
date_format_time = "%B %e, %Y %I.%M %p"

Date.strptime(current_date, date_format_time).iso8601
#=> "2022-12-21"

Btw. I suggest http://strftime.net/ to play around and analyze with strptime's format codes.

  • Related