SkaveRat
SkaveRat

Reputation: 2282

convert String to DateTime

I need to parse following String into a DateTime Object:
30/Nov/2009:16:29:30 +0100

Is there an easy way to do this?

PS: I want to convert the string above as is. The colon after the year is not a typo. I also want to solve the problem with Ruby and not RoR.

Upvotes: 129

Views: 213932

Answers (8)

Siwei
Siwei

Reputation: 21569

convert string to date:

# without timezone
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000

# with specified timezone
DateTime.strptime('2012-12-09 00:01:36 +8', '%Y-%m-%d %H:%M:%S %z')
=> Sun, 09 Dec 2012 00:01:36 +0800

refer to: https://ruby-doc.org/stdlib-3.1.1/libdoc/date/rdoc/Date.html

Upvotes: 17

Kaleb Brasee
Kaleb Brasee

Reputation: 51945

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

Upvotes: 117

user1425976
user1425976

Reputation: 327

This will convert the string in date to datetime, if using Rails:

"05/05/2012".to_time

Doc Reference: https://apidock.com/rails/String/to_time

Upvotes: 26

xentek
xentek

Reputation: 2645

Shouldn't this also work for Rails?

"30/Nov/2009 16:29:30 +0100".to_datetime

Upvotes: 135

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You can parse a date time string with a given timezone as well:

zone = "Pacific Time (US & Canada)"
ActiveSupport::TimeZone[zone].parse("2020-05-24 18:45:00")
=> Sun, 24 May 2020 18:45:00 PDT -07:00

Upvotes: 2

declan
declan

Reputation: 5635

I used Time.parse("02/07/1988"), like some of the other posters.

An interesting gotcha was that Time was loaded by default when I opened up IRB, but Time.parse was not defined. I had to require 'time' to get it to work.

That's with Ruby 2.2.

Upvotes: 15

Automatico
Automatico

Reputation: 12916

I have had success with:

require 'time'
t = Time.parse(some_string)

Upvotes: 57

Wayne Conrad
Wayne Conrad

Reputation: 107999

in Ruby 1.8, the ParseDate module will convert this and many other date/time formats. However, it does not deal gracefully with the colon between the year and the hour. Assuming that colon is a typo and is actually a space, then:

#!/usr/bin/ruby1.8

require 'parsedate'

s = "30/Nov/2009 16:29:30 +0100"
p Time.mktime(*ParseDate.parsedate(s))    # =>  Mon Nov 30 16:29:30 -0700 2009

Upvotes: 5

Related Questions