Rails: how to create Time object in specific time zone - ruby-on-rails

My app is working in "Moscow" (+04:00) timezone. But sometimes I need to create time object by only local time (for example "01 may 2012 13:45") and name of ActiveSupport::TimeZone object (for example "Berlin": +02:00 in Summer Time and +01:00 otherwise).
For example if I get "01 may 2012 13:45" and "Berlin" as input I want to yield "2012-05-01 13:45:00 +0200" or "2012-05-01 11:45:00 +0000". I create following function:
def from_local_datetime(local_datetime, time_zone)
offset = Time.now.in_time_zone(time_zone).formatted_offset
datetime = case local_datetime
when String
DateTime.parse(local_datetime)
else
DateTime.new(local_datetime)
end.change(:offset => offset)
return datetime
end
And at the first look it works as I expected. But is it a best practice for this kind of task? May be in some situation It works with errors. I'm not definitely sure.
I would be greatful to any comments.
UPD: I think bug may occur about time when DST changing the time. For example 26 march 2011 was GMT+1 in Berlin time zone and Time.now.in_time_zone("Berlin").formatted_offset returns "GMT+1", but it would be GMT+2 in 27 march 2011. So if I call from_local_datetime("28 march 2011", "Berlin") before 27 march it returns 28 march 2011 00:00:00 +0100, but If I call it after changing the time my function returns 28 march 2011 00:00:00 +0200 :(

Your conversion method is the right approach.
With web sites, you should make sure times are stored as UTC in the database. If you can get the UTC value out of the database, instead of the local time (or maybe you can set your web server's time zone to UTC) it won't have to convert the time from UTC to local time, when you are going to then convert it to the user's timezone anyway.
And, of course, you will have to store the user's time zone preference.

TZInfo::Timezone.get('Europe/London')
Find the time zone
http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

Related

Create TimeWithZone object from integer (unix epoch time with millisecond precision) and with specified zone (string)

I have an integer that represents a unix epoch time in millisecond precision and a time zone string. I need to create a TimeWithZone object with them.
epoch_ms_integer = 1586653140000
time_zone = "America/Los_Angeles"
Trying to convert to:
Sat, 11 Apr 2020 20:59:00 PDT -07:00
I was able to accomplish this by doing:
Time.at(epoch_ms_integer/1000).asctime.in_time_zone("America/Los_Angeles")
but was wondering if this is the best way to achieve this. The app I'm working on is configured to EST/EDT time zone so Time.at(epoch_ms_integer/1000) returns 2020-04-11 20:59:00 -0400.
I was able to find the asctime solution in one of the answers here Ruby / Rails - Change the timezone of a Time, without changing the value
the same question was asked here but no answer converting epoch time with milliseconds to datetime.
Assuming that the timestamp is in milliseconds, then 1586653140000 is
Epoch: 1586653140
GMT: Sunday, April 12, 2020 12:59:00 AM
PDT: Saturday, April 11, 2020 17:59:00 PM -in time zone America/Los Angeles
These are just 3 different ways to refer to a specific point in time around the world.
Sat, 11 Apr 2020 20:59:00 PDT -07:00 and 2020-04-11 20:59:00 -0400 each refer to different points in time and not the same as epoch(1586653140)
Since the Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), it wouldn't make sense to take 1586653140 and only change the time zone without adding the zone's offset because now you are talking about another point in time.
To get the right "translation" from the epoch to any time zone you could just do
Time.zone = "GMT"
Time.zone.at(1586653140)
=> Sun, 12 Apr 2020 00:59:00 GMT +00:00
Time.zone = "America/Los_Angeles"
Time.zone.at(1586653140)
=> Sat, 11 Apr 2020 17:59:00 PDT -07:00
When working with dates in time zones in rails it is important to only use functions that take the set time zone into account:
DON’T USE
Time.now
Date.today
Date.today.to_time
Time.parse("2015-07-04 17:05:37")
Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
DO USE
Time.current
2.hours.ago
Time.zone.today
Date.current
1.day.from_now
Time.zone.parse("2015-07-04 17:05:37")
Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone
Also keep in mind that in a Rails app, we have three different time zones:
system time,
application time, and
database time.
This post by thoughtbot explains things clearly.

Daylight Savings Time ignored using in_time_zone Rails 4

I'm having a frustrating issue that I can't seem to narrow down. I have searched many similar articles but they are not close enough to my issue to resolve. I am trying to pull a time from the database and display it in more than one time zone. My Rails app is using UTC as default. Here is what I'm doing:
On the create action I take the string of time which will be saved in the time column in my DB:
params[:schedule][:start] = "09:00"
Time.zone = "Central Time (US & Canada)"
#schedule.start = Time.zone.parse(params[:schedule][:start])
The above formats the time as it is supposed to:
2016-04-12 09:00:00 -0500
This is saved in the DB as:
2000-01-01 14:00:00
This has no time offset which is fine since I know it's in UTC. The problem happens when I go to display the time:
#schedule.start.in_time_zone("Central Time (US & Canada)")
This returns:
Sat, 01 Jan 2000 08:00:00 CST -06:00
Now, since this is a time column, I don't care about the date. I plan on formatting the value to only show the time. However, it is showing CST when it is currently CDT.
I can't figure out why this is happening. As I said I am not setting the Time Zone anywhere in my application.rb or anywhere else and I only set the Time zone on the create action which should be fine when moving to a new action.
Any help on clarifying this would be awesome!
This seems to be because when the time is stored it is stored with the date in the year 2000-01-01 which seems to be why it is using CST. How can I ignore the date when converting it to a particular timezone or will I need to change the column type to DateTime to get this to work properly?
It is showing CST simply because the time is read from the database including the stored date, i.e. it's read as 09:00 of Jan 1st 2000.
I guess you'd have to parse the time upon reading the attribute back. You can use a helper method in your model, for example:
# schedule model
def start_in_zone(zone)
self.start.strftime("%H:%M").in_time_zone(zone)
end
This will take only the hours and minutes part of the stored time and parse it in the given time zone with the date set to today. See this example:
"Sat, 01 Jan 2000 08:00:00".to_time.
strftime("%H:%M").
in_time_zone("Central Time (US & Canada)")
# => Tue, 12 Apr 2016 08:00:00 CDT -05:00
The fact that it matters whether it's CST or CDT means you do, on some level, care about the date. While I'm not familiar with the exact rules of Daylight Savings in that region, I do know that Jan 1 is the middle of winter and will definitely not be on Daylight Savings time.
Add the relevant date into your #schedule before putting it into a time zone, and it should fix the problem.

Rails query find result with partiular day with where cluase

I want to orders which are confirmed particular day.
This is particular day:
today = Time.zone.now
Wed, 10 Jun 2015 13:31:16 IST +05:30
This is range of particular day
value = today.beginning_of_day()..today.end_of_day()
Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30
But when I execute this, SQL query date range is changed,
orders = Order.where(confirmed_at: value)
SELECT "orders".* FROM "orders" WHERE "orders"."confirmed_at" BETWEEN '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999' ORDER BY orders.confirmed_at DESC
In this orders confiremed between '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999'
But I wants confirmed between 'Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30'
You can use Time.zone.now.to_time for today.
today = Time.zone.now.to_time
value = today.beginning_of_day()..today.end_of_day()
I hope this helps.
Which DB are you using?
ActiveRecord will declare time columns using data types that do not support timezones. For example, in Postgres it will use timestamp without time zone.
This means that all Time, DateTime and TimeWithZone values set on an ActiveRecord object will be written to the DB as UTC.
Rails will then take care to apply and remove the right offsets each time the values are read or written, using the current value of Time.zone (e.g. for the current web request).
Just check the docs for TimeWithZone and think about what should go in your WHERE clause.
It probably depends on the specific context, but you might have to use UTC values in your query.

Moment JS Show Local Time from DateTime.UTCNow

I have a JSON method which is returning a UTC DateTime I am storing on the server. It returns the following:
/Date(1394155885817)/
I'm trying to figure out how to get Moment JS to show me the local (browser) time. So my timezone is -5 (EST) I'd want to see 3:31 instead of 8:31. See the fiddle below.
http://jsfiddle.net/R9UbS/
What am I doing wrong here? How can I force Moment to return local?
I just ran the fiddle in Romania and got 3:31. Also, javascript's Date constructor handles UTC millis correctly. You're getting 8:31 which makes me think it's doing what it's supposed to do, showing the local time. Why is 8:31 incorrect? And is your device's timezone set correctly? (Btw if your timezone is GMT -5 then you would indeed get 8:31 PM the previous day)
Just to put this a bit in perspective, i put the number in a milliseconds to time converter and i saw that 1394155885817 actually means Fri Mar 07 2014 1:31:25 AM in UTC (or GMT for convenience) - subtracting 5 hours from this would result in Fri Mar 06 2014 8:31:25 PM

Why does this rails query behave differently depending on timezone?

I have a rails time-based query which has some odd timezone sensitive behaviour, even though as far as I know I'm using UTC. In a nutshell, these queries give different answers:
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours).gmtime]).length
=> 279
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours)]).length
=> 280
Where the DB actually does contain one model created in the last hour, and the total number of models is 280. So only the first query is correct.
However, in environment.rb I have:
config.time_zone = 'UTC'
The system time zone (as reported by 'date') is BST (which is GMT+1) - so somehow this winds up getting treated as UTC and breaking queries.
This is causing me all sorts of problems as I need to parameterise the query passing in different times to an action (which are then converted using Time.parse()), and even though I send in UTC times, this 'off by one hour' DST issue crops a lot. Even using '.gmtime()' doesn't always seem to fix it.
Obviously the difference is caused somehow by an implicit conversion somewhere resulting in BST being incorrectly treated as UTC, but why? Doesn't rails store the timestamps in UTC? Isn't the Time class timezone aware? I am using Rails 2.2.2
So what is going on here - and what is the safe way to program around it?
edit, some additional info to show what the DB and Time class are doing:
>> Model.find(:last).created_at
=> Tue, 11 Aug 2009 20:31:07 UTC +00:00
>> Time.now
=> Tue Aug 11 22:00:18 +0100 2009
>> Time.now.gmtime
=> Tue Aug 11 21:00:22 UTC 2009
The Time class isn't directly aware of your configured timezone. Rails 2.1 added a bunch of timezone support, but Time will still act upon your local timezone. This is why Time.now returns a BST time.
What you likely want is to interact with Time.zone. You can call methods on this like you would the Time class itself but it will return it in the specified time zone.
Time.zone.now # => Tue, 11 Aug 2009 21:31:45 UTC +00:00
Time.zone.parse("2:30 PM Aug 23, 2009") # => Sun, 23 Aug 2009 14:30:00 UTC +00:00
Another thing you have to be careful with is if you ever do queries on the database where you are comparing times, but sure to use the UTC time (even if you have a different time zone specified) because Rails always stores UTC in the database.
Item.all(:conditions => ["published_at <= ?", Time.now.utc])
Also, instead of Time.now-1.hour do 1.hour.ago. It is easier to read and Rails will automatically use the configured timezone.
The TimeZone you need to set is UK, this will automatically handle BST
Time.zone = 'UK'
Time.zone.now
=> Sun, 17 Oct 2010 02:09:54 BST +01:00
start_date_format = DateTime.strptime(#start_date, date_format)
start_date_format_with_hour =
DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
end_date_format = DateTime.strptime(#end_date, date_format)
end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
#filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour

Resources