Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert date string to Date where Day is missing

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading