This is probably trivial for anybody who knows the tzinfo API:
Given a Timezone object from tzinfo, how can I get the UTC offset at a given point in time (given either in local time of the Timezone or UTC)?
You can use the period_for_local method. For these examples, I'm using the timezone I live in (America/Sao_Paulo), in where the offset is -03:00 during winter (March to October) and -02:00 during summer (Daylight Saving Time):
# Sao Paulo timezone
zone = TZInfo::Timezone.new('America/Sao_Paulo')
# date in January (Brazilia Summer Time - DST)
d = DateTime.new(2017, 1, 1, 10, 0)
period = zone.period_for_local(d)
puts period.offset.utc_total_offset / 3600.0
# date in July (Brazilia Standard Time - not in DST)
d = DateTime.new(2017, 7, 1, 10, 0)
period = zone.period_for_local(d)
puts period.offset.utc_total_offset / 3600.0
The output is:
-2.0
-3.0
The utc_total_offset method returns the offset in seconds, so I divided by 3600 to get the value in hours.
Note that I also used 3600.0 to force the results to be a float. If I just use 3600, the results will be rounded and timezones like Asia/Kolkata (which has an offset of +05:30) will give incorrect results (5 instead of 5.5).
Note that you must be aware of DST changes, because you can have either a gap or a overlap.
In São Paulo timezone, DST starts at October 15th 2017: at midnight, clocks shift forward to 1 AM (and offset changes from -03:00 to -02:00), so all the local times between 00:00 and 01:00 are not valid. In this case, if you try to get the offset, it will get a PeriodNotFound error:
# DST starts at October 15th, clocks shift from midnight to 1 AM
d = DateTime.new(2017, 10, 15, 0, 30)
period = zone.period_for_local(d) # error: TZInfo::PeriodNotFound
When DST ends, at February 18th 2018, at midnight clocks shift back to 11 PM of 17th (and offset changes from -02:00 to -03:00), so the local times between 11 PM and midnight exist twice (in both offsets).
In this case, you must specify which one you want (by setting the second parameter of period_for_local), indicating if you want the offset for DST or not:
# DST ends at February 18th, clocks shift from midnight to 11 PM of 17th
d = DateTime.new(2018, 2, 17, 23, 30)
period = zone.period_for_local(d, true) # get DST offset
puts period.offset.utc_total_offset / 3600.0 # -2.0
period = zone.period_for_local(d, false) # get non-DST offset
puts period.offset.utc_total_offset / 3600.0 # -3.0
If you don't specify the second parameter, you'll get a TZInfo::AmbiguousTime error:
# error: TZInfo::AmbiguousTime (local time exists twice due do DST overlap)
period = zone.period_for_local(d)
It seems in Ruby 1.9.3 there is some hackery (DateTime to Time) involved, with possible loss of precision, but this is my result based on the answer from #Hugo:
module TZInfo
class Timezone
def utc_to_local_zone(dateTime)
return dateTime.to_time.getlocal(self.period_for_utc(dateTime).utc_total_offset)
end
def offset_to_s(dateTime, format = "%z")
return utc_to_local_zone(dateTime).strftime(format)
end
end
end
Related
ZonedDateTime zdt = ZonedDateTime.of(2015, 10, 18, 0, 30, 0, 0,
ZoneId.of("America/Sao_Paulo"));
System.out.println(zdt); // 2015-10-18T01:30-02:00[America/Sao_Paulo]
You can see the hour is 1 while we set the hour as 0, and timezone is UTC-02:00 while daylight saving timezone should be UTC-03:00.
But here is a different example:
ZonedDateTime zdt = ZonedDateTime.of(2015, 10, 18, 0, 30, 0, 0,
ZoneId.of("America/Los_Angeles"));
System.out.println(zdt); //2015-10-18T00:30-07:00[America/Los_Angeles]
You can see the daylight saving timezone is UTC-07:00 and the hour is 0 as we set.
Why are they different?
This happens because the time you picked falls in the gap between midnight and 01:00 on the night when Brazil switches to summer time. That time is actually impossible and so you get the behavior described in the documentation:
In the case of a gap, when clocks jump forward, there is no valid offset. Instead, the local date-time is adjusted to be later by the length of the gap. For a typical one hour daylight savings change, the local date-time will be moved one hour later into the offset typically corresponding to "summer".
You can observe the same behavior in Los_Angeles zone by picking a time between 02:00 and 03:00 on the corresponding night in March:
zdt = ZonedDateTime.of(2015, 3, 8, 2, 30, 0, 0,
ZoneId.of("America/Los_Angeles"));
System.out.println(zdt);
As already explained in #Misha's answer, it happens due to Daylight Saving Time rules.
In São Paulo, DST starts at the midnight of 2015-10-18: the clocks move forward 1 hour, so it "jumps" from 23:59:59 to 01:00:00. There's a gap between 00:00:00 and 00:59:59, so the time 00:30 is adjusted accordingly.
You can check if the date and time are valid for the timezone using the ZoneRules and ZoneOffsetTransition classes:
ZoneId sp = ZoneId.of("America/Sao_Paulo");
ZoneRules rules = sp.getRules();
// check if 2015-10-18 00:30 is valid for this timezone
LocalDateTime dt = LocalDateTime.of(2015, 10, 18, 0, 30);
List<ZoneOffset> validOffsets = rules.getValidOffsets(dt);
System.out.println(validOffsets.size()); // size is zero, no valid offsets at 00:30
The getValidOffsets method returns all the valid offsets for the specified date/time. If the list is empty, it means the date/time doesn't "exist" in that timezone (usually because of DST the clocks jump forward).
When the date/time exists in a timezone, an offset is returned:
ZoneId la = ZoneId.of("America/Los_Angeles");
rules = la.getRules();
validOffsets = rules.getValidOffsets(dt);
System.out.println(validOffsets.size()); // 1 - date/time valid for this timezone
System.out.println(validOffsets.get(0)); // -07:00
For Los_Angeles timezone, 1 valid offset is returned: -07:00.
PS: Offset changes usually occur due to DST, but that's not always the case. DST and offsets are defined by governments and laws, and they can change at anytime. So, a gap in the valid offset can also mean that such change occured (some politician decided to change the standard offset of the country, so the gap might not necessarily be related to DST).
You can also check when the change occurs, and what's the offset before and after it:
ZoneId sp = ZoneId.of("America/Sao_Paulo");
ZoneRules rules = sp.getRules();
// get the previous transition (the last one that occurred before 2015-10-18 00:30 in Sao_Paulo timezone
ZoneOffsetTransition t = rules.previousTransition(dt.atZone(sp).toInstant());
System.out.println(t);
The output is:
Transition[Gap at 2015-10-18T00:00-03:00 to -02:00]
It means that there's a gap (clocks moving forward) at 2015-10-18T00:00, and the offset will change from -03:00 to -02:00 (so, clock moves 1 hour forward).
You can also get all these info separately:
System.out.println(t.getDateTimeBefore() + " -> " + t.getDateTimeAfter());
System.out.println(t.getOffsetBefore() + " -> " + t.getOffsetAfter());
The output is:
2015-10-18T00:00 -> 2015-10-18T01:00
-03:00 -> -02:00
It shows that, at 00:00 the clock moves directly to 01:00 (so 00:30 can't exist). In the second line, the offsets before and after the change.
If you check the transitions in Los_Angeles timezone, you'll see that its DST starts and ends at different dates:
ZoneId la = ZoneId.of("America/Los_Angeles");
rules = la.getRules();
// 2015-10-18 00:30 in Los Angeles
Instant instant = dt.atZone(la).toInstant();
System.out.println(rules.previousTransition(instant));
System.out.println(rules.nextTransition(instant));
The output is:
Transition[Gap at 2015-03-08T02:00-08:00 to -07:00]
Transition[Overlap at 2015-11-01T02:00-07:00 to -08:00]
So, in Los_Angeles timezone, DST starts at 2015-03-08 and ends at 2015-11-01. That's why at 2015-10-18, all hours are valid (there's no adjustment as it happens in Sao_Paulo timezone).
Some timezones have transition rules (like "DST starts at the third Sunday of October") instead of just transitions (like "DST starts at this specific date and time"), and you can also use them, if available:
ZoneId sp = ZoneId.of("America/Sao_Paulo");
ZoneRules rules = sp.getRules();
// hardcoded: Sao_Paulo timezone has 2 transition rules, the second one is relative to October
// but you should always check if the list is not empty
ZoneOffsetTransitionRule tr = rules.getTransitionRules().get(1);
// get the transition for year 2015
ZoneOffsetTransition t = tr.createTransition(2015);
// use t the same way as above (the output will be the same)
Another way to check if a date and time is valid for some timezone is to use the ZonedDateTime.ofStrict method, that throws an exception if the date and time is invalid for a timezone:
ZoneId sp = ZoneId.of("America/Sao_Paulo");
ZoneId la = ZoneId.of("America/Los_Angeles");
LocalDateTime dt = LocalDateTime.of(2015, 10, 18, 0, 30);
System.out.println(ZonedDateTime.ofStrict(dt, ZoneOffset.ofHours(-7), la)); // OK
System.out.println(ZonedDateTime.ofStrict(dt, ZoneOffset.ofHours(-3), sp)); // throws java.time.DateTimeException
The first case is OK, because an offset of -7 is valid for Los Angeles, for the given date/time. The second case throws an exception because an offset of -3 is invalid for São Paulo, at the given date/time.
I want to compare two Time objects only down to the hour, while ignoring the difference of minutes and seconds.
I'm currently using t0.strftime("%Y%m%d%H") == t1.strftime("%Y%m%d%H"), but I don't think this is a good solution.
Is there better way to do this?
You can use this trick in pure Ruby
t0.to_a[2..9] == t1.to_a[2..9]
Where Time#to_a
$> Time.now.to_a
# => [7, 44, 2, 8, 3, 2014, 6, 67, false, "GMT"]
# [ sec, min, hour, day, month, year, wday, yday, isdst, zone ]
So you can check that the times are equals or not up to the level you want and without missing important components of the object like the zone, etc.
If you have ActiveSupport (either through Rails, or just installed as a gem), it includes an extension to the Time class that adds a change method which will truncate times:
$> require "active_support/core_ext/time"
# => true
$> t = Time.now
# => 2014-03-07 21:30:01 -0500
$> t.change(hour: 0)
# => 2014-03-07 00:00:00 -0500
This won't modify the original time value either. So you can do this:
t0.change(minute: 0) == t1.change(minute: 0)
It'll zero out everything at a lower granularity (seconds, etc.).
require 'time'
t1 = Time.new ; sleep 30 ; t2 = Time.new
t1.hour == t2.hour
This should give you a boolean answer.
I would like to know how to get the current week number from Rails and how do I manipulate it:
Translate the week number into date.
Make an interval based on week number.
Thanks.
Use strftime:
%U - Week number of the year. The week starts with Sunday. (00..53)
%W - Week number of the year. The week starts with Monday. (00..53)
Time.now.strftime("%U").to_i # 43
# Or...
Date.today.strftime("%U").to_i # 43
If you want to add 43 weeks (or days,years,minutes, etc...) to a date, you can use 43.weeks, provided by ActiveSupport:
irb(main):001:0> 43.weeks
=> 301 days
irb(main):002:0> Date.today + 43.weeks
=> Thu, 22 Aug 2013
irb(main):003:0> Date.today + 10.days
=> Sun, 04 Nov 2012
irb(main):004:0> Date.today + 1.years # or 1.year
=> Fri, 25 Oct 2013
irb(main):005:0> Date.today + 5.months
=> Mon, 25 Mar 2013
You are going to want to stay away from strftime("%U") and "%W".
Instead, use Date.cweek.
The problem is, if you ever want to take a week number and convert it to a date, strftime won't give you a value that you can pass back to Date.commercial.
Date.commercial expects a range of values that are 1 based.
Date.strftime("%U|%W") returns a value that is 0 based. You would think you could just +1 it and it would be fine. The problem will hit you at the end of a year when there are 53 weeks. (Like what just happened...)
For example, let's look at the end of Dec 2015 and the results from your two options for getting a week number:
Date.parse("2015-12-31").strftime("%W") = 52
Date.parse("2015-12-31").cweek = 53
Now, let's look at converting that week number to a date...
Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
If you blindly just +1 the value you pass to Date.commercial, you'll end up with an invalid date in other situations:
For example, December 2014:
Date.commercial(2014, 53, 1) = ArgumentError: invalid date
If you ever have to convert that week number back to a date, the only surefire way is to use Date.cweek.
date.commercial([cwyear=-4712[, cweek=1[, cwday=1[, start=Date::ITALY]]]]) → date
Creates a date object denoting the given week date.
The week and the day of week should be a negative
or a positive number (as a relative week/day from the end of year/week when negative).
They should not be zero.
For the interval
require 'date'
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime("%m/%d/%y" )
end
puts week_dates(22)
EG: Input (Week Number): 22
Output: 06/12/08 - 06/19/08
credit: Siep Korteling http://www.ruby-forum.com/topic/125140
Date#cweek seems to get the ISO-8601 week number (a Monday-based week) like %V in strftime (mentioned by #Robban in a comment).
For example, the Monday and the Sunday of the week I'm writing this:
[ Date.new(2015, 7, 13), Date.new(2015, 7, 19) ].map { |date|
date.strftime("U: %U - W: %W - V: %V - cweek: #{date.cweek}")
}
# => ["U: 28 - W: 28 - V: 29 - cweek: 29", "U: 29 - W: 28 - V: 29 - cweek: 29"]
I need to calculate the offset, in hours, of a given timezone from UTC in Ruby. This line of code had been working for me, or so I thought:
offset_in_hours = (TZInfo::Timezone.get(self.timezone).current_period.offset.utc_offset).to_f / 3600.0
But, it turns out that was returning to me the Standard Offset, not the DST offset. So for example, assume
self.timezone = "America/New_York"
If I run the above line, offset_in_hours = -5, not -4 as it should, given that the date today is April 1, 2012.
Can anyone advise me how to calculate offset_in_hours from UTC given a valid string TimeZone in Ruby that accounts for both standard time and daylight savings?
Thanks!
Update
Here is some output from IRB. Note that New York is 4 hours behind UTC, not 5, because of daylight savings:
>> require 'tzinfo'
=> false
>> timezone = "America/New_York"
=> "America/New_York"
>> offset_in_hours = TZInfo::Timezone.get(timezone).current_period.utc_offset / (60*60)
=> -5
>>
This suggests that there is a bug in TZInfo or it is not dst-aware
Update 2
Per joelparkerhender's comments, the bug in the above code is that I was using utc_offset, not utc_total_offset.
Thus, per my original question, the correct line of code is:
offset_in_hours = (TZInfo::Timezone.get(self.timezone).current_period.offset.utc_total_offset).to_f / 3600.0
Yes, use TZInfo like this:
require 'tzinfo'
tz = TZInfo::Timezone.get('America/Los_Angeles')
To get the current period:
current = tz.current_period
To find out if daylight savings time is active:
current.dst?
#=> true
To get the base offset of the timezone from UTC in seconds:
current.utc_offset
#=> -28800 which is -8 hours; this does NOT include daylight savings
To get the daylight savings offset from standard time:
current.std_offset
#=> 3600 which is 1 hour; this is because right now we're in daylight savings
To get the total offset from UTC:
current.utc_total_offset
#=> -25200 which is -7 hours
The total offset from UTC is equal to utc_offset + std_offset.
This is the offset from the local time where daylight savings is in effect, in seconds.
~ Approximate Solar Noon
lw = 88.743 # my longitude
jdate = Date.ordinal_to_jd(Time.now.year, Time.now.yday)
n = (jdate - 2451545 - 0.0009 - lw / 360).round # lw is users longitude west of 0.
j_noon = 2451545 + 0.0009 + lw / 360 + n
puts j_noon
=> 2455616.24740833
As an update, part of the confusion would be that solar noon is where all
calculations started since January 1, 4713 BC Greenwich noon.
The correct use of Date.ordinal_to_jd has not compensated for this fact. So by
adding or subtracting 12 hours like this:
jdn = Date.ordinal_to_jd(Time.now.year, Time.now.yday) - 0.5
we should get less errors. Just which do we use though since our calculations
start with yesterdays noon?
The code is derived from the two equations from this page Sunrise_equation.
The first answer I got from a user here was that we don't understand the use of
0.0009 and lw / 360. lw / 360 would appear to be a fractional day of arc from the
prime meridian. As for the 0.0009, it must be a small amount of variance in
seconds since January 1, 4713 BC Greenwich noon. see IAU standards for more info
I calculate it to be 0.007776 seconds according to this page.
I have a little bit of info from Date class not including method details.
=begin
--------------------------------------------------------------------- Class: Date
Class representing a date.
See the documentation to the file date.rb for an overview.
Internally, the date is represented as an Astronomical Julian Day Number, ajd.
The Day of Calendar Reform, sg, is also stored, for conversions to other date formats.
(There is also an of field for a time zone offset,
but this is only for the use of the DateTime subclass.)
A new Date object is created using one of the object creation class methods named
after the corresponding date format, and the arguments appropriate to that date
format; for instance, Date::civil()
(aliased to Date::new()) with year, month, and day-of-month, or Date::ordinal() with
year and day-of-year.
All of these object creation class methods also take the Day of Calendar Reform as an
optional argument.
Date objects are immutable once created.
Once a Date has been created, date values can be retrieved for the different date
formats supported using instance methods. For instance, #mon() gives the Civil month,
#cwday() gives the Commercial day of the week, and #yday() gives the Ordinal day of
the year. Date values can be retrieved in any format, regardless of what format was
used to create the Date instance.
The Date class includes the Comparable module, allowing date objects to be compared
and sorted, ranges of dates to be created, and so forth.
---------------------------------------------------------------------------------
Includes:
Comparable(<, <=, ==, >, >=, between?)
Constants:
MONTHNAMES: [nil] + %w(January February March April May June July August
September October November December)
DAYNAMES: %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
ABBR_MONTHNAMES: [nil] + %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
ABBR_DAYNAMES: %w(Sun Mon Tue Wed Thu Fri Sat)
ITALY: 2299161
ENGLAND: 2361222
JULIAN: Infinity.new
GREGORIAN: -Infinity.new
Class methods:
_load, _parse, _strptime, ajd_to_amjd, ajd_to_jd, amjd_to_ajd, civil, civil_to_jd,
commercial, commercial_to_jd, day_fraction_to_time, gregorian?, gregorian_leap?, jd,
jd_to_ajd, jd_to_civil, jd_to_commercial, jd_to_ld, jd_to_mjd, jd_to_ordinal,
jd_to_wday, julian?, julian_leap?, ld_to_jd, mjd_to_jd, new, now, ordinal,
ordinal_to_jd, parse, s3e, strptime, time_to_day_fraction, today, valid_civil?,
valid_commercial?, valid_jd?, valid_ordinal?, valid_time?
Instance methods:
+, -, <<, <=>, ===, >>, _dump, ajd, amjd, asctime, civil, commercial, ctime, cwday,
cweek, cwyear, day, day_fraction, downto, england, eql?, gregorian, gregorian?, hash,
hour, inspect, italy, jd, julian, julian?, ld, leap?, mday, min, mjd, mon, month,
new_offset, new_start, next, next_day, offset, ordinal, sec, sec_fraction, start,
step, strftime, succ, time, to_s, to_yaml, upto, wday, weeknum0, weeknum1, wnum0,
wnum1, yday, year, zone
=end
As a side note, it's great that Ruby has a way to calculate the julian-date.
I'm looking into the Javascript code from NOAA.
Here is a class that I was inspired to write by the link.
class JulianDayNumber
def initialize(year = 2000, month = 1, day = 1) #defaults to Jan. 01, 2000
#year = year
#month = month
#day = day
end
def calcJDN
if (#month <= 2) then
#year -= 1
#month += 12
end
varA = (#year/100).floor
varB = 2 - varA + (varA/4).floor
jdn = (365.25*(#year + 4716)).floor \
+ (30.6001*(#month+1)).floor \
+ #day + varB - 1524.5
return jdn
end
end
jd = JulianDayNumber.new(2011, 3, 2)
julianday = jd.calcJDN
puts julianday
=> 2455622.5
Now this gets me there but I'm still researching for the way back for a number such
as the one calculated by the top most equation. Trying this we can see that we do
get a 0.5 in the JDN. Who is right? Ruby or NOAA?
NOAA uses the January 1st 2000 value of 2451545.0 that is subtracted from the jd to get time
in fractional century like this
def calcTimeJulianCent(j)
t = (j - 2451545.0)/36525.0
return t
end
Ruby has a number of ways of calculating Julian Day and you need to pick the right one. NOAA is calculating the JD since January 1, 4713 BC Greenwich noon as you know. It always ends in .5 because they are leaving out the fractional days.
Ruby's Julian Day is weird:
For scientific purposes, it is
convenient to refer to a date simply
as a day count, counting from an
arbitrary initial day. The date first
chosen for this was January 1, 4713
BCE. A count of days from this date is
the Julian Day Number or Julian Date,
which is abbreviated as jd in the Date
class. This is in local time, and
counts from midnight on the initial
day.
Which makes no sense for astronomical use. but wait..
The stricter usage is in UTC, and
counts from midday on the initial day.
This is referred to in the Date class
as the Astronomical Julian Day Number,
and abbreviated as ajd. In the Date
class, the Astronomical Julian Day
Number includes fractional days.
(rubydoc)
This is what you are looking for, ajd. Just get it without the fractional days:
julianday = Date.civil(#year, #month, #day).ajd
puts julianday
=> 2455622.5
No need to port 9 lines of JavaScript from NOAA. Ruby's got your back! ;)
Well thanks everybody, I guess that I can answer my own question now. I overlooked a simple method in the Date class. It is Date.day_fraction_to_time(day fractional). As I have a working program now I would like to share it with eveyone.
include Math
to_r = PI / 180.0
to_d = 180.0 / PI
latitude = 41.9478 # my latitude
longitude = 88.74277 # my longitude
lw = longitude / 360
jdate = Date.civil(Time.now.year, Time.now.month, Time.now.day).ajd
jdate = (jdate * 2).to_i/2 + 1
n = (jdate - 2451545 - 0.0009 - lw).round
j_noon = 2451545 + 0.0009 + lw + n
mean_anomaly = (357.52911 + 0.98560028 * (jdate - 2451545)) % 360
center = 1.9148 * sin(mean_anomaly * to_r) + 0.0200 * sin(2 * mean_anomaly * to_r) + \
0.0003 * sin(3 * mean_anomaly * to_r)
lambda = (mean_anomaly + 102.9372 + center + 180) % 360
j_transit = j_noon + (0.0053 * sin(mean_anomaly * to_r)) - (0.0069 * sin(2 * lambda * \
to_r))
delta = asin(0.397753054 * sin(lambda * to_r)) * to_d
omega = acos(sin(-0.83 * to_r)/cos(latitude * to_r) * cos(delta * to_r) \
- tan(latitude * to_r) * tan(delta * to_r)) * to_d
j_set = 2451545 + 0.0009 + ((omega + longitude)/360 + n + 0.0053 * sin(mean_anomaly * \
to_r)) - 0.0069 * sin(2 * lambda * to_r)
j_rise = j_transit - (j_set - j_transit)
rise = Date.day_fraction_to_time(j_rise - jdate)# + 0.25 for + 6 hours
risehour = rise[0].to_s
risemin = rise[1].to_s
risetime = "#{risehour}:#{risemin}"
puts "Sun rise = #{risetime} UTC"
transit = Date.day_fraction_to_time(j_transit - jdate)# + 0.25
transithour = transit[0].to_s
transitmin = transit[1].to_s
transittime = "#{transithour}:#{transitmin}"
puts "Solar noon = #{transittime} UTC"
set = Date.day_fraction_to_time(j_set - jdate)# + 0.25
sethour = set[0].to_s
setmin = set[1].to_s
settime = "#{sethour}:#{setmin} UTC"
puts "Sun set = #{settime}"
The method ordinal_to_jd converts the day with index 0 of the year 2011 (Gregorian calendar) to the corresponding day in the Julian calendar, then you are using the magical value of 0.0009 for which i dont know any reason, then you are adding the ratio of your longitude (east or west?) of the whole 360* circle and then adding todays day-of-year (54 if you evaluated it today). The combination of Julian calendar and longitudinal ratio makes not much sense, but hey its a nice number since you mixed a 0.0009 in.