Question

I know this sounds like a repeated question but I think this situation is different. I will delete this post if it truly is.

I have a string containing a date in the following format: Thu, Jun. 20

I would like to parse this into a Date variable and then increment it to the next day.

So far I have done

text = "Thu, Jun. 20"
date = Date.new
date = Date.strptime(text, '{%a, %m, %d}')

But this gives me the following error:

invalid date (ArgumentError)

I got this idea from: Ruby: convert string to date

All answers I have seen so far have been parsing strings that contain full information (the full month or day of the week). Is what I'm trying to do even possible ? If not any suggestions on a work around would be most appreciated.

Was it helpful?

Solution 2

To answer your need I would like to parse this into a Date variable and then increment it to the next day. I tried below :

require 'date'

d = Date.parse("Thu, Jun. 20") 
# => #<Date: 2013-06-20 ((2456464j,0s,0n),+0s,2299161j)>
d.to_s # => "2013-06-20"
d.next.to_s # => "2013-06-21"

OTHER TIPS

You used wrong date format. After parse it, you can use plus or minus operator to change date.

Reference: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-i-strftime

%a - The abbreviated name (``Sun'')

%b - The abbreviated month name (``Jan'')

%d - Day of the month, zero-padded (01..31)

Code:

1.9.3p392 :003 > require 'date'
 => true 
1.9.3p392 :008 > date = Date.strptime(text, '%a, %b. %d')
 => #<Date: 2013-06-20 ((2456464j,0s,0n),+0s,2299161j)> 
1.9.3p392 :009 > date + 1
 => #<Date: 2013-06-21 ((2456465j,0s,0n),+0s,2299161j)> 
1.9.3p392 :010 > date - 1
 => #<Date: 2013-06-19 ((2456463j,0s,0n),+0s,2299161j)> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top