Reputation: 851
I need to get time and date
from database date like "2015-08-27T12:09:36Z"
. I tried but not get any solutions where I get date and time in different variable.
I need to get it in Ruby
. No rails
in my application.
I used below code but not getting.
Time.strptime("2015-08-27T12:09:36Z", "%Y-%m-%dT%H:%M:%S%z").in_time_zone
Any one have a experience in it?
Thanks
Upvotes: 1
Views: 307
Reputation: 95385
First, you need to require 'date'
. Ruby has built-in Date
and Time
classes without that require
, but the library provides more functionality.
If you have a string retrieved from the database in ISO-8601 format, and you want to turn it into a date and time, just use DateTime.iso8601(string)
to get a DateTime
object. You can extract the date and time components however you like after that.
irb(main):001:0> require 'date' #=> true
irb(main):002:0> dt = DateTime.iso8601("2015-08-27T12:09:36Z") # DateTime object
irb(main):003:0> d = dt.to_date # Date object
irb(main):004:0> t = dt.to_time # Time object
Upvotes: 1
Reputation: 576
I don't have enough reputations to comment so am posting comment as answer, are you looking for this
Time.now.strftime('%Y-%m-%dT%H:%M:%SZ')
Which will give the pattern you asked for. Z represent the time zone if you use
%z - Time zone as hour and minute offset from UTC (e.g. +0900)
%:z - hour and minute offset from UTC with a colon (e.g. +09:00)
%::z - hour, minute and second offset from UTC (e.g. +09:00:00)
%Z - Time zone abbreviation name
Check for more
http://apidock.com/ruby/Time/strftime
My Updated answer after your comment
require 'date'
DateTime.parse("2015-08-27T12:09:36Z").strftime('%Y-%m-%dT%H:%M:%SZ')
In your code change Time.strptime('')
to DateTime.strptime('')
Upvotes: 1