scientiffic
scientiffic

Reputation: 9415

Get UTC offset in Ruby

I'm trying to get the UTC offset for a datetime. The datetime is saved as:

Fri, 31 May 2013 15:19:08 EDT -04:00

What I'd like to get is "-04:00". When I do object.utc_offset, I get -14400. What function should I use?

Upvotes: 9

Views: 4501

Answers (3)

vgoff
vgoff

Reputation: 11313

You are looking for strftime:

Time.now.strftime("%:z")

That will give you the offset such as "-04:00".

Upvotes: 18

bayendor
bayendor

Reputation: 276

vgoff and Matt Johnson beat me to it, but for further elaboration see page 717-720 and table 27.18 in Programming Ruby 3rd Edition (The Pickaxe book), for further elaboration. %z gives hour offsets, %Z gives the time zone name, e.g. MDT, PST, etc.

Upvotes: -1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

Its in seconds. Divide by 3600 for hours, or 60 for minutes.

But if you want the formatted offset string, use vgoff's answer.

Upvotes: 3

Related Questions