`DateTime.strptime` returns an invalid date for the day of the week / time string

Why Ruby strptime does not convert this to a DateTime object:

 DateTime.strptime('Monday 10:20:20', '%A %H:%M:%S') # => ArgumentError: invalid date 

So far, this work?

 DateTime.strptime('Wednesday', '%A') # => #<DateTime: 2015-11-18T00:00:00+00:00 ((2457345j,0s,0n),+0s,2299161j)> DateTime.strptime('10:20:20', '%H:%M:%S') # => #<DateTime: 2015-11-18T10:20:20+00:00 ((2457345j,37220s,0n),+0s,2299161j)> 
+6
source share
1 answer

It looks like a bug - minitech comment . So far, a workaround (because you probably want this to work now):

You can break it into a space, get the date from the workday, then get the time component from another line (using the _strptime method). Then you can set the time on the first date to the time component from the second line:

 def datetime_from_weekday_time_string(string) components = string.split(" ") date = DateTime.strptime(components[0], '%A') time = Date._strptime(components[1], '%H:%M:%S') # returns a hash like {:hour=>10, :min=>20, :sec=>20} return date.change(time) end 2.2.2 :021 > datetime_from_weekday_time_string("Monday 10:20:20") => Mon, 16 Nov 2015 10:20:20 +0000 2.2.2 :022 > datetime_from_weekday_time_string("Saturday 11:45:21") => Sat, 21 Nov 2015 11:45:21 +0000 2.2.2 :023 > datetime_from_weekday_time_string("Thursday 23:59:59") => Thu, 19 Nov 2015 23:59:59 +0000 
+2
source

All Articles