moorecats
moorecats

Reputation: 3492

How would I go about converting this time string to epoch time in ruby?

How would I go about converting 2012-12-13T14:43:35.371Z to epoch time?

One approach I was considering was to strip the T and Z and then try to use the DateTime library to find a way to convert to epoch. Before I go down that path, I was curious if there is a gem I could use to do this quickly. On a related note, I will be doing time calculations after I convert to epoch.

Upvotes: 7

Views: 10291

Answers (3)

berkes
berkes

Reputation: 27553

require "date"
DateTime.parse("2012-12-13T14:43:35.371Z").strftime("%s")

In cases where you need more control over parse, use strptime, which allows you to define a string that explains the format.

Upvotes: 1

rausch
rausch

Reputation: 3388

For example:

require 'date'

# as an integer:
DateTime.parse('2012-12-13T14:43:35.371Z').to_time.to_i
# or as a string:
DateTime.parse('2012-12-13T14:43:35.371Z').strftime('%s')

Upvotes: 14

sawa
sawa

Reputation: 168101

require "time"
Time.iso8601("2012-12-13T14:43:35.371Z").to_i

Upvotes: 2

Related Questions