Do not use the parse method or anything on it for this.
In the USA, we use “MM / DD / YYYY”, but Ruby, which has a more universal bent, assumes “DD / MM / YYYY”, which can cause a lot of crashes if the day was> 12. It will also change the values of the day and month.
If today is January 2, 2000, parse will receive the day / month ago in the date strings in the USA:
DateTime.parse('1/2/2000 12:00AM')
If the date is December 31, 2000, parse will break:
DateTime.parse('12/31/2000 12:00AM')
Ruby assumes the first day:
DateTime.parse('31/12/2000 12:00AM')
Attempting to get around this situation by sniffing a date string will fail. The only way to make sure you can parse the date strings correctly is to know the date format used by the user or the software that generated the string, or always use ISO-based strings that are defined as a specific format.
Instead, give up the convenience of guessing something and tell Ruby which format to use:
require 'date' DateTime.strptime('12/31/2000 12:00AM', '%m/%d/%Y %H:%M%p')
source share