Ruby Parse Date String

Parse Date string in Ruby

You could use the Date.strptime method provided in Ruby's Standard Library:

require 'date'
string = "20120723"
date = Date.strptime(string,"%Y%m%d")

Alternately, as suggested in the comments, you could use Date.parse, because the heuristics work correctly in this case:

require 'date'
string = "20120723"
date = Date.parse(string)

Both will raise an ArgumentError if the date is not valid:

require 'date'
Date.strptime('2012-March', '%Y-%m')
#=> ArgumentError: invalid date

Date.parse('2012-Foo') # Note that '2012-March' would actually work here
#=> ArgumentError: invalid date

If you also want to represent hours, minutes, and so on, you should look at DateTime. DateTime also provides a parse method which works like the parse method on Date. The same goes for strptime.

convert String to DateTime

DateTime.strptime allows you to specify the format and convert a String to a DateTime.

Convert string to datetime ruby on rails

You can use DateTime to parse the date from a specific format.

if the format you are looking to parse is "03/28/2018 1:46 AM" then you can do this.

date = DateTime.strptime('03/28/2018 1:46 AM', '%m/%d/%Y %I:%M %p')

# date to ISO 8601

puts date.to_time
# output: 2018-03-28 07:16:00 +0530

puts date.strftime("%m/%d/%Y")
# output: 03/28/2018

Date formats:

Date (Year, Month, Day):

%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)

Time (Hour, Minute, Second, Subsecond):

%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)
%l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')

%M - Minute of the hour (00..59)

You can refer to all formats here.

Parsing a date string in Ruby

You can use Time.zone.at to parse a timestamp in seconds.

response = {"StartDate"=>"/Date(1532563200000+0000)/", "ExpirationDate"=>"/Date(1564099200000+0000)/"}

start_date = Time.zone.at(response['StartDate'][6..15].to_i)
#=> Wed, 25 Jul 2018 20:00:00 EDT -04:00

expiration_date = Time.zone.at(response['ExpirationDate'][6..15].to_i)
#=> Thu, 25 Jul 2019 20:00:00 EDT -04:00

Parsing date using strftime

Here's some code that might help:

require 'date'
require 'time'

date = Date.strptime('2015-04-28 19:30:00 UTC', "%Y-%m-%d %H:%M:%S %Z")
# => #<Date: 2015-04-28 ((2457141j,0s,0n),+0s,2299161j)>
date.strftime('%m/%d/%y')
# => "04/28/15"

Parsing into a Date object stores only the year, month and day information.

datetime = DateTime.strptime('2015-04-28 19:30:00 UTC', "%Y-%m-%d %H:%M:%S %Z")
# => #<DateTime: 2015-04-28T19:30:00+00:00 ((2457141j,70200s,0n),+0s,2299161j)>
datetime.strftime('%m/%d/%y')
# => "04/28/15"

time = Time.strptime('2015-04-28 19:30:00 UTC', "%Y-%m-%d %H:%M:%S %Z")
# => 2015-04-28 19:30:00 UTC
time.strftime('%m/%d/%y')
# => "04/28/15"

Parsing into a DateTime, or Time object captures all the information.

The error you're seeing is often caused by a date string in a format you don't expect. That often happens when you expect a value in 'mm/dd/yy' order, but actually receive one in 'dd/mm/yy' order. This happens because the US uses 'mm/dd/yy' and most of the rest of the world uses 'dd/mm/yy':

date = Date.strptime('2015-28-04', '%Y-%m-%d')
# ~> -:7:in `strptime': invalid date (ArgumentError)

or

date = Date.strptime('28-04-2015', '%m-%d-%Y')
# ~> -:7:in `strptime': invalid date (ArgumentError)

You can work around that by using some rescue statements to try several different formats.

You don't want to use parse because it'll assume 'dd/mm/yyyy' and will blow up with US dates, and is slower because it tries multiple formats before giving up. So, using fixed formats you expect is the way to go but you need to search for your various formats of date/datetime strings you'll expect to find and write format strings to match. And, since you're scraping pages, it's possible to find a LOT of bad/malformed values so program defensively.

Ruby - convert string to date

For Ruby 1.9.2:

require 'date'    # If not already required. If in Rails then you don't need this line).
puts DateTime.parse("2011-06-02T23:59:59+05:30").to_date.to_s


Related Topics



Leave a reply



Submit