Parse a Date in Rails

Parse a date in rails

You can try Date.parse(date_string).

You might also use Date#strptime if you need a specific format:

> Date.strptime("10/15/2013", "%m/%d/%Y")
=> Tue, 15 Oct 2013

For a general solution:

format_str = "%m/%d/" + (date_str =~ /\d{4}/ ? "%Y" : "%y")
date = Date.parse(date_str) rescue Date.strptime(date_str, format_str)

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.

Rails date check if parsable

You have to try parsing the string and rescue ArgumentError

begin
myDate = Date.parse("31-01-2016")
rescue ArgumentError
# handle invalid date
end

one line (please note that this rescues all errors)

myDate = Date.parse("31-01-2016") rescue nil

Rails: Date.parse vs string.to_date

If you check the code here, you'll see that the second way of doing this really just invokes the first method with only a minor check for blank-ness.

def to_date
::Date.parse(self, false) unless blank?
end

Regarding the false argument, consulting the docs here:

If the optional second argument is true and the detected year is in the range “00” to “99”, considers the year a 2-digit form and makes it full.

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%C - year / 100 (round down. 20 in 2009)
%y - year % 100 (00..99)

%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%B - The full month name (``January'')
%^B uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
%^b uppercased (``JAN'')
%h - Equivalent to %b

%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)

%j - Day of the year (001..366)

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)

%S - Second of the minute (00..59)

%L - Millisecond of the second (000..999)
%N - Fractional seconds digits, default is 9 digits (nanosecond)
%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
%12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

ruby DateTime parsing from 'mm/dd/yyyy' format


require 'date'
my_date = Date.strptime("12/22/2011", "%m/%d/%Y")

Proper way to parse and format a DateTime object?

See DateTime#strftime:

> DateTime.now.strftime '%m-%d-%Y'
=> "08-22-2014"

And please, please, please don’t use that format, unless you have no choice. Hyphens should only be used for the Y-m-d format. Use slashes or dots if possible. (Even better, use Y-m-d!)



Related Topics



Leave a reply



Submit