Convert date string to Date where Day is missing

Advertisements

I know i can use to_date or parse to convert a string to a date in rails, but how do i convert to a date if the string is of the format "01-2018", where 01 is the month (January) and the day is missing ? Must be simple but i am having trouble doing it.

Trying it returns unexpected results, I am guessing because the day is missing:

3.0.2 :004 > Date.parse(x)  => Sun, 01 Jan 2023
3.0.2 :005 > x  => "01-2018"
3.0.2 :006 > x.to_date  => Sun, 01 Jan 2023

I guess i can prefix the string with sth like "01-", but is there a better way?

>Solution :

You can use Date.strptime. This method receives the string and format of the date:

date_str = "01-2023"
date = Date.strptime(date_str, "%m-%Y")
puts date # 2023-01-01

Leave a Reply Cancel reply