I have a datestring in this format
yyyy-mm-ddThh:mm:ss[Z]
And i have a timezone string. for e.g "Asia/Kolkata"
Now i want to convert this date string into the timezone of the given timezone
for e.g. if the date is 2014-01-03T23:30:00Z , then in "Asia/Kolkata" timezone it will be 2014-01-04T05:00:00 .
I tried using Time library , but Time library does not seem to have any method which can convert to other timzone http://ruby-doc.org/core-1.8.6/Time.html#method-c-mktime .
You should use the TZInfo gem.
require 'tzinfo'
tz = TZInfo::Timezone.get('Asia/Kolkata')
utc = DateTime.iso8601('2014-01-03T23:30:00Z')
local = tz.utc_to_local(utc)
If it just a ruby project without rails, also you do not want to install third party gems.
Then you have to do it yourself, the following is what I did:
def convert_time_to_timezone(time, timezone)
timezone_in_hours = timezone.to_i
time_in_seconds = time.to_i
time_in_seconds_in_timezone = time_in_seconds + timezone_in_hours*3600
utc_time = Time.at(time_in_seconds_in_timezone).utc
Time.new(utc_time.year, utc_time.month, utc_time.day, utc_time.hour, utc_time.min, utc_time.sec, "#{timezone}:00")
end
Just provide time (e.g., Time.now) and timezone (e.g., "+11:00", or "-05:00")
it will return the time with the specified timezone.
example:
call convert_time_to_timezone(Time.now, "+11:00") it will return something like
2017-05-31 18:17:13 +1100
If it has rails installed, then you can directly call in_time_zone('"Central Time (US & Canada)"')
Related
Hi I would like to subtract time from a CSV array using Ruby
time[0] is 12:12:00AM
time[1] is 12:12:01AM
Here is my code
time_converted = DateTime.parse(time)
difference = time_converted[1].to_i - time_converted[0].to_i
p difference
However, I got 0
p time[0].to_i gives me 12
is there a way to fix this?
You can use Time#strptime to define the format of the parsed string.
In your case the string is %I:%M:%S%p.
%I = 12 hour time
%M = minutes
%S = seconds
%p = AM/PM indicator
So to parse your example:
require 'time'
time = %w(12:12:00AM 12:12:01AM)
parsed_time = time.map { |t| Time.strptime(t, '%I:%M:%S%p').to_i }
parsed_time.last - parsed_time.first
=> 1
Use the Ruby DateTime class and parse your dates into objects of that class.
I have three strings, pulled from a database:
"2015-03-18" (the date the event occurs)
"22:00" (the hour an event occurs)
"-05:00" (the UTC offset in the location the event occurs).
I want to combine these three strings to produce a Ruby Time object. I'm doing:
utc_offset = "-05:00"
airtime = "22:00"
airday = "2015-03-18"
year,month,day,hour,minutes = airday.split("-").map(&:to_i) + airtime.split(":").map(&:to_i)
Time.new(year,month,day,hour,minutes,0,utc_offset)
This works; I'm just wondering if it's the correct/standard/idiomatic/clearest way.
By using Time.parse
When ‘time’ is required, Time is extended with additional methods for
parsing and converting Times.
require 'time'
utc_offset = "-05:00"
airtime = "22:00"
airday = "2015-03-18"
time = Time.parse("#{airday} #{airtime} #{utc_offset}")
I think this is the way to do it.
Time.new(*airday.split("-"), *airtime.split(":"), 0, utc_offset)
How about this? http://ruby-doc.org/stdlib-2.1.5/libdoc/time/rdoc/Time.html#method-c-strptime
require 'time'
raw_time = '2015-03-18 22:00'
parsed_time = Time.strptime(raw_time, '%Y-%m-%d %H:%M') # 2015-03-18 22:00:00 +0100
I am fetching data from a mysql database in a non rails project using ruby. The data has a TIMESTAMP type, how can I convert it to a ruby date/time object so that I can do date comparisons on it?
These are some of the values coming from the db:
2014-03-17 22:56:02
2011-05-17 21:46:22
Use ::strptime
require 'date'
string = '2014-03-17 22:56:02'
DateTime.strptime(string, "%Y-%m-%d %H:%M:%S")
# => #<DateTime: 2014-03-17T22:56:02+00:00 ((2456734j,82562s,0n),+0s,2299161j)>
Try this
t = Time.at(<msqlTimestamp>)
puts t.to_date
I need to try to get a TZInfo style string a-la 'America/New_York' representing the local timezone of the system I'm on. I can't figure out how to do it.
Time.zone
#<ActiveSupport::TimeZone:0x007ff2e4f89240 #name="UTC", #utc_offset=nil, #tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, #current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffsetInfo: 0,0,UTC>>>>
Here the TimezoneProxy#Etc/UTC field is the style I want but is UTC not local time.
Time.now.zone
"EST"
Here the "EST" is not what I want and I don't see a way to pass Time.now or EST to TZInfo to get what I want?
Is there a way to get "America/New_York" or even a list of all equivalent timezone strings based on my current timezone?
You can try to find all EST aliases with:
current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
all.
select{|tz| tz.utc_offset == current_tz.utc_offset }.
map(&:tzinfo).
map(&:name).
uniq
will produce
["America/Bogota", "EST", "America/New_York", "America/Indiana/Indianapolis", "America/Lima"]
But I think this is incorrect, because of daylight saving issues. More correct code:
current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
all.
select{|tz|
tz.utc_offset == current_tz.utc_offset &&
tz.tzinfo.current_period.dst? == current_tz.tzinfo.current_period.dst?
}.
map(&:tzinfo).
map(&:name).
uniq
will produce
["America/Bogota", "EST", "America/Lima"]
I am working on an application in which I need to get the current year, month, and day. Is there a way to get this information in the pre block of a rule?
Can I get this data as a string or a number or both?
There are currently time functions documented on http://docs.kynetx.com/docs/Time but none of them seem to work for what I am trying to do.
Is there a way to set the timezone when getting this data?
I was able to do it using strftime which appears to be an undocumented feature so use with caution.
ruleset a60x518 {
meta {
name "date-test"
description <<
date-test
>>
author "Mike Grace"
logging on
}
rule testing {
select when pageview ".*"
pre {
retTime = time:strftime(time:now({"tz":"America/Denver"}), "%c");
month = time:strftime(time:now({"tz":"America/Denver"}), "%B");
year = time:strftime(time:now({"tz":"America/Denver"}), "%Y");
day = time:strftime(time:now({"tz":"America/Denver"}), "%d");
}
{
notify("time",retTime) with sticky = true;
notify("month",month) with sticky = true;
notify("year",year) with sticky = true;
notify("day",day) with sticky = true;
}
}
}
App run on example.com twice. Once with the timezone set to New York and onother time set to Denver
I used this site http://www.statoids.com/tus.html to get the correct strings to use for the timezone. I have no idea if they all work. I just found this site and tried a few and they worked so use with caution.
Perhaps the docs got reverted. For convenience, here is the documentation for strftime:
time:strftime()
Convert a datetime string to a different format
Usage
time:strftime(`<string>`,`<format>`)
Valid format arguments to strftime follow the POSIX strftime conventions.
Samples
time:strftime(xTime,”%F %T”) # 2010-10-06 18:15:24
time:strftime(xTime,”%F”) # 2010-10-06
time:strftime(xTime,”%T”) # 18:19:29
time:strftime(xTime,”%A %d %b %Y”) # Wednesday 06 Oct 2010
time:strftime(xTime,”%c”) # Oct 6, 2010 6:25:55 PM
The other time functions:
time:now()
Current datetime based upon user’s location data
Usage
time:now()
time:now({“tz” : <timezone>)
time:new()
Create a new RFC 3339 datetime string from a string (allows some flexibility in how the source string is formatted)
Usage
time:new() # Equivalent to time:now()
time:new(<string>)
Valid formats for the datetime source string can be found in ISO8601 (v2000).
time:add()
Add (or subtract) a specific number of time units to a source string
Usage
time:add(<string>,{<unit> : n})