Ruby - Convert String to Date

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

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

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.

Ruby - Convert a string to Date

if you want date object

date_string = "25/04/14"
date = Date.strptime(date_string, "%d/%m/%y")

if you want 25-04-2014 format string

new_format = date.strftime("%d-%m-%Y")

Converting string to date with Ruby

Remove the period from my_string and from the date pattern.

Date.strptime(my_string.sub('.', ''), '%d %b %Y')

That's assuming you have at most one dot in my_string. If there may be several, use gsub.

Date.strptime(my_string.gsub('.', ''), '%d %b %Y')

Convert string to date time in Ruby

Here you go:

DateTime.strptime("03/30/2021 4:30 PM", "%m/%d/%Y %H:%M %p") # =>  Tue, 30 Mar 2021 16:30:00 +0000

And here is the strptime method, https://ruby-doc.org/stdlib/libdoc/date/rdoc/DateTime.html

How to convert string(cointaining offset) to date/time in rails

Not knowing Rails, I will give a pure-Ruby answer (which may be of interest in its own right). For this reason, I cannot help with the extraction of the time zone name. I understand that can be done with Rails or by installing the tzinfo gem.

We begin with a given string:

str = "2018-06-16 22:39:09 +0200"

In Ruby we will need use of various methods from the classes Time and DateTime, so we must require 'time' or require 'date' (not required by Rails, I am told). Note DateTime.superclass #=> Date.

require 'time'

The first step is to create a DateTime object from this string. Two ways of doing that are to use DateTime::parse or DateTime::strptime, the latter being the more demanding and therefore more reliable method.

dtp = DateTime.parse(str)
#=> #<DateTime: 2018-06-16T22:39:09+02:00 ((2458286j,74349s,0n),+7200s,2299161j)>
dt = DateTime.strptime(str, '%Y-%m-%d %H:%M:%S %z')
#=> #<DateTime: 2018-06-16T22:39:09+02:00 ((2458286j,74349s,0n),+7200s,2299161j)>

Another approach is to convert the string to an array and then use DateTime::new or Time::new:

*all_but_last, offset = str.split(/[- :]/)
#=> ["2018", "06", "16", "22", "39", "09", "+0200"]
all_but_last
#=> ["2018", "06", "16", "22", "39", "09"]
offset
#=> "+02:00"
arr = [*all_but_last.map(&:to_i), offset.insert(-3, ':')]
#=> [2018, 6, 16, 22, 39, 9, "+02:00"]
DateTime.new(*arr)
#=> #<DateTime: 2018-06-16T22:39:09+02:00 ((2458286j,74349s,0n),+7200s,2299161j)>
Time.new(*arr)
#=> 2018-06-16 22:39:09 +0200

For the time being, trust me that UTC times are in fact instances of Time.

Browsing the methods of the class Time we find that it provides all the methods we need to convert between UTC time and local time, namely Time.gmtime, Time#utc_offset (aka, gmt_offset) and Time#getlocal.

The next step, therefore, is to convert the DateTime object dt to a time object, using DateTime#to_time:

t = dt.to_time
#=> 2018-06-16 22:39:09 +0200

We may now convert this Time instance to a UTC time:

ut = t.gmtime
#=> 2018-06-16 20:39:09 UTC

My earlier assertion that UTC times are Time instances can now be confirmed:

ut.class
#=> Time

To convert this back to a local time we must save the local time's UTC offset:

offset = t.utc_offset
#=> 7200

This offset is measured in seconds for GMT (7200/3600 = 2 hours).

We may now compute the local time from ut and offset:

ut.getlocal(offset)
#=> 2018-06-16 22:39:09 +0200

Ruby: convert string to date

You could also use Date.strptime:

Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")

Convert String to DateTime Ruby

require 'date'

▶ Date.parse "2015-11-01T10:00:00.00+08:00"
#⇒ #<Date: 2015-11-01 ((2457328j,0s,0n),+0s,2299161j)>

▶ DateTime.parse "2015-11-01T10:00:00.00+08:00"
#⇒ #<DateTime: 2015-11-01T10:00:00+08:00 ((2457328j,7200s,0n),+28800s,2299161j)>

or, even better:

▶ DateTime.iso8601 "2015-11-01T10:00:00.00+08:00"
#⇒ #<DateTime: 2015-11-01T10:00:00+08:00 ((2457328j,7200s,0n),+28800s,2299161j)>


Related Topics



Leave a reply



Submit