Convert particular timezone to UTC timezone - ruby-on-rails

For example my local time_zone is Canada and i am getting date in Chennai timezone. How can I convert the Chennai timezone to UTC?

Using server time
You can call ActiveSupport::TimeWithZone#utc on the result.
Example:
Time.zone.now.utc
Keep in mind that .now is using the server time zone when config.time_zone is set.
When you receive a time
If you are getting the datetime in Chennai timezone it will probably look like this: 2019-11-26T12:20:00.655+05:30
To convert it in different time zone, use:
time = Time.parse("2019-11-26T12:20:00.655+05:30")
pacific_time = time.in_time_zone("Pacific Time (US & Canada)")
# and then UTC if you want
pacific_time.utc

Related

rails- convert time to utc based on browser time zone and start_date

I have browser time zone in a cookie variable and date in start_date variable as string .
say cookie['browser_zone']="Asia/kolkata"
& start_date = "2017/12/31 03:00:00"
how can I convert above date to with this time zone to UTC time zone.
Use ActiveSupport::TimeZone to parse the time into the correct time zone, then convert it to UTC
ActiveSupport::TimeZone["Asia/Kolkata"].parse("2017/12/31 03:00:00").utc
=> 2017-12-30 21:30:00 UTC

Rails: Take an unformatted datetime and assign it a time zone w/o changing the time?

I'm importing an object from an API with a datetime that looks like this:
"2017-06-28 09:00:00"
This time is in the user's time zone, which is known in my application. (i.e. Pacific Time (US & Canada))
Datetimes are stored in my database as datetime format in UTC. When we display dates on the front-end, we account for the user's time zone (ie datetime.in_time_zone(user_time_zone)).
How do I save the datetime in my database correctly?
You should be able to append your apps timezone to the end of the datetime string.
time = "2017-06-28 09:00:00"
time += Time.zone.name
Parsing that will give you the time in Pacific Time (US & Canada). Or use ActiveSupport.
time_pacific = DateTime.parse(time)
### ActiveSupport version ###
time_pacific = ActiveSupport::TimeZone.new(Time.zone.name).parse("2017-06-28 09:00:00")
You can then call #utc on that to get the correct UTC time from your original string.
time_utc = time_pacific.utc

How to set the timezone to EST throughout the rails app?

I want to use EST throughout the app. I have set the
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'
what I want is, I have to get all the time I have used like "DateTime.now" and it now returns time in my local timezone but I want it to return date time in EST. Also I have date time range picker and I get the start date and end date and parse the string to time using
(params[:start_date]).to_time
which also returns the date time in local zone and instead i want all those to return in EST. How can I do this? Any help is appreciated.
Thanks in advance.
DateTime.now and Time.now doesn't respect Time.zone and will always use the server time. If the machine you're using is set to a different timezone, these 2 will use that timezone.
to_time on the other hand defaults to local timezone as mentioned in apidock (although just tried this out and I get utc by default). To get these times in the timezone set, append in_time_zone
DateTime.now.in_time_zone
Time.now.in_time_zone
string.to_time.in_time_zone
There are some shortcuts for these though. The following code will return the timestamps in the current timezone
Time.zone.now
Time.zone.parse(string)
Normally, in database date-time would be saved in UTC format unless you have selected a specific TimeZone for Active Record and it would be easier if you have to meddle with multiple TimeZones. But, while you access the values you will get the values in you selected TimeZone.
config.time_zone = 'Eastern Time (US & Canada)
Now, suppose you have a datetime value in UTC from table as
datetime1 = "2014-08-25 10:25:57 +0000"
You can convert it to the selected timezone 'Eastern Time (US & Canada)' as below,
Time.zone.parse(datetime1) => Mon, 25 Aug 2014 06:25:57 EDT -04:00
Then, if you need it in a proper format, use method strftime.
Time.zone.parse("2014-08-25 10:25:57 +0000").strftime("%d-%m-%Y %H:%M:%S") => "25-08-2014 06:25:57"
Hoep it helps :)

Different date saved to database - wrong time zone

When I fetch a date from FullCalendar with Javascript I have the following values:
Fri Sep 13 2013 08:30:33 GMT-0400 (EDT)
After I save that date to database I see that in database there are different values:
2013-09-13 12:00:00.000000
So, date is automatically converted to UTC and saved like that into database. How to save the correct date into database? I don't want to hardcode it :)
Thank you.
For that you need to define your time zone in your application.rb
config.time_zone = 'YOUR-TIME-ZONE'
config.active_record.default_timezone = :local
config.active_record.time_zone_aware_attributes = false
By default, the rails app timezone is UTC. Whenever the record is saved the date, datetime, time fields are saved with DB's timezone but when they are fetched back in models it is converted back to UTC.
So, in your case set your application timezone in application.rb like this
config.time_zone = 'Central Time (US & Canada)'
Now, whenever the records are fetched from database it will always be converted to CST timezone irrespective of DBs timezone.
Hope this will help.

Rails: How to parse date-time string into a specific time zone

I'm using Rails 3.2 and ruby 1.9.3 on Debian. I have an app that collects a date, time, and timezone in the form of strings via an HTML form. Something like this:
start_date: "04-15-2010",
start_time: "10:00:00",
timezone: "Central Time (US & Canada)"
What I'd like to do is parse these 3 elements into a single date that is saved into my database as UTC, which in this case would add 7 hours to the start time, once it's in the UTC time zone.
So the stored time would be 17:00 once it's in the DB as UTC instead of the received Central time.
I have tried something like this to parse the date:
ActiveSupport::TimeZone[timezone].at DateTime.strptime("{ 2012-04-09 20:00:00 }", "{ %Y-%m-%d %H:%M:%S }").to_i
However, I'm not able to incorporate the time zone into the resulting time with %Z. It either doesn't parse or the time is interpreted as UTC not Central time. So my question is, how to coerce a date string into a certain time zone without changing the value of the actual date/time stored. I'd like to be able to parse the string into a date/time object that includes the correct time zone with it at that time so that future time zone conversions are accurate. I've looked all over and can't find a way to do this. It's strange, since this seems like something common one does with dates inputted from HTML forms. Thank you for any help.
Try this:
zone = "Central Time (US & Canada)"
ActiveSupport::TimeZone[zone].parse("2013-04-03 17:47:00")
Use String#in_time_zone (Rails 4+)
I personally prefer using String#in_time_zone:
>> '22.09.1986 10:30'.in_time_zone('Central Time (US & Canada)')
# => Mon, 22 Sep 1986 10:30:00 CDT -05:00
This parses the date and time in the String into the time zone provided.
%Z is the correct way to specify a Time zone name. Have you tried the following ?
date_and_time = '%m-%d-%Y %H:%M:%S %Z'
DateTime.strptime("04-15-2010 10:00:00 Central Time (US & Canada)",date_and_time)
This is the method that I came up with. Not the prettiest, but it works. Allows parsing the string using a specified format, and then turning it into the format that I know Time.zone.parse requires.
class ActiveSupport::TimeZone
def strptime(time, format='%m/%d/%Y')
formatted = Time.strptime(time, format).strftime('%Y-%m-%d %T')
parse(formatted)
end
end
Then you can do something like what was mentioned in another question, but with a specified format:
zone = "Central Time (US & Canada)"
ActiveSupport::TimeZone[zone].strptime('2013-04-03', '%Y-%m-%d')
Or if you already have a time zone set:
Time.zone = "Central Time (US & Canada)"
Time.zone.strptime('01/13/2006')
I used a default format of %m/%d/%Y because that's what my user input is most of the time. You can customize this to your needs, or use the default format DateTime uses which is believe is iso8601 (%FT%T%z)
I've finally found the dirty, yet definitive way to do this.
First, parse the string using plain Ruby Time.strptime like this:
time = Time.strptime('12 : 00 : PM', '%I : %M : %p')
This way you get the parsed Time, but not yet in correct timezone. To fix that, let's convert the time to string form and parse it with the standard ActiveSupport::TimeZone#parse
Time.zone.parse(time.to_s)
The result is the ActiveSupport::TimeWithZone with our time parsed into the correct timezone.
The reason why we have to do it this way is that neither ActiveSupport::TimeZone nor ActiveSupport::TimeWithZone support the strptime method. So we have to parse the Time with core Ruby strptime that does not have timezone information, convert it to format acceptable in ActiveSupport objects and then parse it yet again.
To have DateTime take the date string and attach a timezone other than UTC without changing the values of the date string , use this, its easy , doesnt break on leap day :)
xx = DateTime.strptime("9/1/15 #{object.time_zone}", "%m/%d/%Y %Z")
Convert specific date format in UTC.
ActiveSupport::TimeZone['UTC'].parse(Time.strptime('01/24/2019T16:10:16', "%m/%d/%YT%H:%M:%S").asctime)

Resources