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
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('')
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
Related
All the existing answers either use a lib or Rails. I need to do this in plain Ruby. I also find it hard to imagine that a beautiful language like Ruby would make this so difficult.
I have many date strings of the form: 07 Nov 20. I am able to parse these into a DateTime instance using:
> require 'time'
=> true
> DateTime.strptime("07 Nov 20", "%d %b %y")
=> #<DateTime: 2020-11-07T00:00:00+00:00 ((2459161j,0s,0n),+0s,2299161j)>
> _.new_offset("+05:30")
=> #<DateTime: 2020-11-07T05:30:00+05:30 ((2459161j,0s,0n),+19800s,2299161j)>
As we can see, using DateTime#new_offset changes not only the offset, but also change the time. There doesn't seem to exist any other method to only change the timezone and/or offset either.
If possible, I'd also like to do this for that individual DateTime instance and not all DateTime instances created in the future via some TIMEZONE global or something.
Note: While the input string doesn't contain any time component, I still need my runtime representation to have one. So while using a simpler method like Date#strptime would work, it is not "ideal".
Note 2: I'm guessing there are other complications with simply "setting" the timezone, which is why this function is not present. For example it is not obvious how to handle DST when you "set" the timezone. I'm guessing that changing the time is going to be inevitable if you want to ensure that passing in a valid offset will always return a valid DateTime instance.
Edit 1:
Further digging in the source code for date (date/date_core.c) reveals the set_of function is used to set the offset for a DateTime instance. Unfortunately, it seems that the logic of manipulating the offset is coupled with the manipulation of the time. This explains why there is no method exposed in the Ruby stdlib to only set the offset.
Should they be Date objects instead? Dates don't have times nor time zones.
Date.strptime("07 Nov 20", "%d %b %y")
Otherwise, you can add a time zone to the string and parse it.
string = "07 Nov 20"
p DateTime.strptime("#{string}+0530", "%d %b %y %z")
Or you can subtract the extra hours. DateTime subtracts number of days and will take a fraction.
DateTime.strptime("07 Nov 20", "%d %b %y").new_offset("+05:30") - 5.5/24
What's the difference between strptime and strftime? I see that strptime is a method in the DateTime class, and strftime is a method in the Time class.
What's the difference between Time and DateTime, other than that they have different core methods? The explanation for the Time class in the Ruby docs is helpful, but the one for DateTime just says "datetime". There's also the Date class, which says it provides Date and DateTime. Help me make sense of this.
I see strptime and I want to pronounce it "strip time", but that doesn't make sense. Is there a good mnemonic-device for it?
What do strptime and strftime mean, anyway?
How do you remember which does what?
The difference between Time and DateTime has to do with implementation. A large amount of the DateTime functionality comes from the Rails world and is an arbitrary date with time of day. It's more of a calendar-based system. Time is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.
In short, DateTime is what you get from a database in Rails where Time is what Ruby has traditionally used. If you're working with values where dates are important and you want to know things like the end of the month or what day it'll be six weeks ahead, use DateTime. If you're just measuring elapsed time and don't care about that, use Time. They're easy to convert between if necessary.
Date on the other hand is just a calendar date and doesn't have any associated times. You might want to use these where times are irrelevant.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification. I've rarely seen strptime used since DateTime.parse is usually good at picking up on what's going on, but if you really need to spell it out, by all means use the legacy parser.
strptime means string parser, this will convert a string format to datetime.
Example:-
datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")
datetime.datetime(2019, 8, 9, 1, 1, 1)//Result
strftime means string formatter, this will format a datetime object to string format.
Example:-
sample_date=datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")
datetime.strftime(sample_date, "%Y-%d-%m %H:%M:%S")
'2019-09-08 01:01:01'//Result
I read the above answer and it is clear in its delineation of Time, DateTime and Date in Ruby.
Time is packaged with Ruby. It is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. More specifically, the Time class stores integer numbers, which presents the seconds intervals since the Epoch. We can think of this as Unix Time. It has some limitations. I read somewhere if stored as a 64-bit signed integer, it can represent dates between 1823-11-12 to 2116-02-20, but on my system it can represent dates outside this range. If you do not specify the timezone to use in the enviroment variable ENV['TZ'], then it will default to your system time found in /etc/localtime on Unix-like systems. When to use Time? It is useful for measuring time elapse or interpolating a timestamp into a string value.
Rails actually extends the Time class. It accomplishes this through ActiveSupport::TimeWithZone. It provides support for configurable time zones. Note Rails will always convert time zone to UTC before it writes to or reads from the database, no matter what time zone you set in the configuration file. In other words, it is the default behaviour of Rails that all your time will get saved into database in UTC format.
# Get current time using the time zone of current local system or ENV['TZ'] if the latter is set.
Time.now
# Get current time using the time zone of UTC
Time.now.utc
# Get the unix timestamp of current time => 1524855779
Time.now.to_i
# Convert from unix timestamp back to time form
Time.at(1524855779)
# USE Rails implementation of Time! Notice we say Time.current rather than Time.now. This will allow you to use the timezone defined in Rails configuration and get access to all the timezone goodies provided by ActiveSupport::TimeWithZone.
Time.current
TimeWithZone provides a lot of very useful helper methods:
# Get the time of n day, week, month, year ago
1.day.ago
1.week.ago
3.months.ago
1.year.ago
# Get the beginning of or end of the day, week, month ...
Time.now.beginning_of_day
30.days.ago.end_of_day
1.week.ago.end_of_month
# Convert time to unix timestamp
1.week.ago.beginning_of_day.to_i
# Convert time instance to date instance
1.month.ago.to_date
For most cases, the Time with the time zone class from Rails’ ActiveSupport is sufficient. But sometimes you just need a date.
Just as with the Time class, Ruby is packaged with the Date class. Simply require the time library:
require "time"
Time.parse("Dec 8 2015 10:19")
#=> 2015-12-08 10:19:00 -0200
Date.parse("Dec 8 2015")
#=> #<Date: 2015-12-08>
Time.new(2015, 12, 8, 10, 19)
#=> 2015-12-08 10:19:00 -0200
Date.new(2015, 12, 8)
Since Date is part of Ruby, it by default uses the timezone defined in /etc/localtime on Unix-like systems, unless you modify the TZ environmental variable. Just as with the Time class, Rails extends the Date class. Use Date.current instead of Date.today to take advantage of ActiveSupport::TimeWithZone and use Rails-based timezone configurations.
Now there is one more class available with regards to dates and times. DateTime is a subclass of Date and can easily handles date, hour, minute, second and offset. It is both available in Ruby (via require 'time') and in Rails (via require 'date'). Rails extends it with TimeZone capabilities just like with the Time class.
require 'date'
DateTime.new(2001,2,3,4,5,6)
I personally do not see a need for using DateTime in your applications, for you can use Time itself to represent dates and times, and you can use Date to represent dates.
The second part of the question was regarding strptime and strftime. Time, Date and DateTime all have the strptime and strftime methods. strptime parses the given string representation and creates an object. Here is an example:
> result = Time.strptime "04/27/2018", "%m/%d/%Y"
=> 2018-04-27 00:00:00 -0400
> result.class
=> Time
This is useful if you have an application and a user submits a form and you are given a date and/or represented as a string. You will want to parse it into a Time or Date before you save it to the database.
strftime formats a date or time. So you call it on a Date or Time object:
> Date.current.strftime("%Y-%m-%d")
=> "2018-04-27"
And you can use them together to first parse user input and then format it in a certain way, perhaps to output into a csv file:
value = Date.strptime(val, '%m/%d/%Y').strftime('%Y-%m-%d')
puts "date --- #{date}"
#date = Time.parse(date.to_s).iso8601 unless date.nil?
puts "#date -- #{#date}"
Outputs
Date --- 2012-08-12T12:15:17-07:00
#Date -- 2012-08-12T19:15:17+00:00
Anyone know why?
Additionally, this happens with strptime
Time.strptime("2012-08-12T12:05:08-07:00", "%Y-%m-%dT%H:%M:%S%:z")
=> 2012-08-12 19:05:08 +0000
It appears that your system is set to UTC. Time.parse() creates a new Time object, which uses the system timezone, and sets it to the time that is parsed. It doesn't change the timezone of the new Time to match the timezone of the parsed date. If you really want that behavior, you can use something like:
DateTime.parse(date.to_s).new_offset(date.iso8601[-6,6]).iso8601
Update: Regarding the strptime() part of the question that was just added, it's the exact same concept. A new Time is being created with the default timezone, with a time that matches the date that you're parsing.
There are at least three types which represent time: Time, Date and DateTime(from ActiveSupport).
My problem is, could DateTime totally replace Date? In other words, if I can use DateTime, is there any reason to use Date instead?
require 'date'
d = Date.today
dt = DateTime.now
p Date.public_methods - DateTime.public_methods
#=>[:today]
p DateTime.public_methods - Date.public_methods
#=>[:now]
p d.public_methods - dt.public_methods
#=>[]
p dt.public_methods - d.public_methods
#=>[:hour, :min, :minute, :sec, :second, :sec_fraction, :second_fraction, :offset, :zone, :new_offset]
DateTime is a subclass of Date. Using DateTime, you lose the today Class method and get now in return. You don't lose instance methods.
If you want to store only the date, for example a birthday, or a certain day where an event takes place, then it can be easier to use only date. Then you have no troubles which arise from different time zones and time zone calculations. If you use DateTime, then if you add an offset of -2 hours to 00:00 am, you get 10:00 pm of the previous day.
Date does not store any information about the time, neither with the timezone. So you might get into trouble if at some point you'll need to use time data.
Cf this link, which I found clear about what classes should be used, when, and how.
I get a string from a external method with a time and date like so "07/09/10 14:50" is there any way I can convert that time in ruby to 'Pacific US' time knowing its 'UTC' time? with changes accounted for in the date? I.e if the time difference results in the day being different.
Since it appears you are using rails, you have quite a few options. I suggest reading this article that talks all about time zones.
To convert to PST, both of these are rails-specific methods. No need to re-invent the wheel:
time = Time.parse("07/09/10 14:50")
time.in_time_zone("Pacific Time (US & Canada)")
Hope this helps
UPDATE: rails might try to get smart and give the time you specify as a string a time zone. To ensure that the time parses as UTC, you should specify in the string:
time = Time.parse("07/09/10 14:50 UTC")
time.in_time_zone("Pacific Time (US & Canada)")
To convert from string form to a date or time object you need to use strptime
require 'date'
require 'time'
my_time_string = "07/09/10 14:50"
to_datetime = DateTime.strptime(my_time_string, "%m/%d/%y %H:%M")
utc_time = Time.parse(to_datetime.to_s).utc
pacific_time = utc_time + Time.zone_offset("PDT")
puts utc_time
puts pacific_time
This is pure ruby, so there are likely some rails-specific methods you could use specifically for this task, but this should get you started.
require 'time'
If you want pacific time just subtract 25200 seconds from Time.new There is a 7 hour difference between pacific time and GMT.
t = Time.parse((Time.new-25200).to_s)
Then use strftime to format however you want it to look.
puts t.strftime("%A %D at %I:%M%p")