i have hex timestamp like this '6132103D' (got it from facebook API) according to this service i get expected date Friday, September 3, 2021 12:08:29 PM.
I have seen such discussion but there is no any success
Cannot use Time.at because i operate with String.
Be thankful if you suggest some solution or gem which i could use.
ruby 2.7.1
rails 6.0.3.2
First you need to convert hex value to decimal.
Then, use Time.at() or DateTime.strptime() function to get the timestamp
2.5.3 :019 > DateTime.strptime(str.to_i(16).to_s, '%s')
=> Fri, 03 Sep 2021 12:08:29 +0000
2.5.3 :020 > Time.at(str.to_i(16))
=> 2021-09-03 17:38:29 +0530
Crossverified using https://www.epochconverter.com/hex
hex timestamp : 6132103D
Equivalent timestamp:
GMT: Friday, September 3, 2021 12:08:29 PM
Your time zone: Friday, September 3, 2021 5:38:29 PM GMT+05:30
Decimal timestamp/epoch: 1630670909
I am using DatePipe to display Epoch time, the milliseconds time is in UTC, I want to keep it display on UTC so I am setting timezone option is '0'.
Here is my code:
<span class="description">{{epochTime | date:'dd/MM/yy hh:mm a':'0'}}</span>
with 'epochTime' = '1570274515223' <=> 'Sat Oct 05 2019 11:21:55 AM'.
But on the UI is: '05/10/19 06:21 PM'
It is getting local time zone here. Why I can not force pipe to use UTC time?
'0' is not valid. Instead, specify the offset in one of the following ways: 0, '+0','+00:00', 'UTC'
https://play.golang.org/p/82QgBdoI2G
package main
import "fmt"
import "time"
func main() {
fmt.Println(time.Now().Format("01-JAN-2006 15:04:00"))
}
The output should be like if date time today is 2016-03-03 08:00:00 +0000UTC
Output: 03-MAR-2016 08:00:00
Time should be in 24hr format.
Your layout is incorrect, it should show how the reference time is represented in the format you want, where the reference time is Mon Jan 2 15:04:05 -0700 MST 2006.
Your layout should be:
"02-Jan-2006 15:04:05"
Note the 05 for the seconds part. And since you specified the hours as 15, that is 24-hour format. 3 or 03 is for the 12-hour format.
fmt.Println(time.Now().Format("02-Jan-2006 15:04:05"))
For me it prints:
03-Mar-2016 13:03:10
Also note Jan for months, JAN is not recognized. If you want uppercased month, you may use strings.ToUpper():
fmt.Println(strings.ToUpper(time.Now().Format("02-Mar-2006 15:04:05")))
Output:
03-MAR-2016 13:03:10
Also note that on the Go Playground the time is always set to a constant when your application is started (which is 2009-11-10 23:00:00 +0000 UTC).
fmt.Println(time.Now().Format("02-Jan-2006 15:04:05"))
See Time package constants
The reference time used in the layouts is the specific time:
Mon Jan 2 15:04:05 MST 2006
which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as
01/02 03:04:05PM '06 -0700
I need to store some time periods in a yaml file, like this:
test:
testing: <%= 1.month %>
I grab the data in an initializer like this:
Class::TIMES = YAML.load(ERB.new(File.new(Rails.root.join('config', 'times.yml')).read).result)
So far so good. But the times I get from this are always off by a day; testing shows this. For example:
<Tue, 06 Mar 2012> expected but was <Wed, 07 Mar 2012>.
The test line:
assert_equal 1.month.from_now.to_date, #object.finished_at.to_date
Elsewhere, #object's finished_at is set like this:
# duration is from the YAML file
self.finished_at = duration.from_now
It always seems to be off by a day, no matter what time period I put in the YAML file. Why does this happen?
EDIT: This seems to be an issue with Fixnums and from_now:
> 1.month.from_now
=> Tue, 06 Mar 2012 21:05:00 UTC +00:00
> 1.month.to_i.from_now
=> Wed, 07 Mar 2012 21:05:05 UTC +00:00
When you convert 1.month to an integer it arbitrary sets the duration getting passed into from_now to 2592000 seconds i.e 30 days regardless of what month it is.
I ran into this issue once before. Check out the documentation for the Data and Time Helper Methods .
While these methods provide precise calculation when used as in the
examples above(".. 1.month.from_now .."), care should be taken to note
that this is not true if the result of months’,years’, etc is
converted before use
I have a variable foo that contains a time, lets say 4pm today, but the zone offset is wrong, i.e. it is in the wrong time zone. How do I change the time zone?
When I print it I get
Fri Jun 26 07:00:00 UTC 2009
So there is no offset, and I would like to set the offset to -4 or Eastern Standard Time.
I would expect to be able to just set the offset as a property of the Time object, but that doesn't seem to be available?
You don't explicitly say how you get the actual variable but since you mention the Time class so I'll assume you got the time using that and I'll refer to that in my answer
The timezone is actually part of the Time class (in your case the timezone is shown as UTC). Time.now will return the offset from UTC as part of the Time.now response.
>> local = Time.now
=> 2012-08-13 08:36:50 +0000
>> local.hour
=> 8
>> local.min
=> 36
>>
... in this case I happen to be in the same timezone as GMT
Converting between timezones
The easiest way that I've found is to change the offset using '+/-HH:MM' format to the getlocal method. Let's pretend I want to convert between the time in Dublin and the time in New York
?> dublin = Time.now
=> 2012-08-13 08:36:50 +0000
>> new_york = dublin + Time.zone_offset('EST')
=> 2012-08-13 08:36:50 +0000
>> dublin.hour
=> 8
>> new_york.hour
=> 3
Assuming that 'EST' is the name of the Timezone for New York, as Dan points out sometimes 'EDT' is the correct TZ.
This takes advantage of the fact that Time#asctime doesn't include the zone.
Given a time:
>> time = Time.now
=> 2013-03-13 13:01:48 -0500
Force it to another zone (this returns an ActiveSupport::TimeWithZone):
>> ActiveSupport::TimeZone['US/Pacific'].parse(time.asctime)
=> Wed, 13 Mar 2013 13:01:48 PDT -07:00
Note that the original zone is ignored completely. If I convert the original time to utc, the result will be different:
>> ActiveSupport::TimeZone['US/Pacific'].parse(time.getutc.asctime)
=> Wed, 13 Mar 2013 18:01:48 PDT -07:00
You can use to_time or to_datetime on the result to get a corresponding Time or DateTime.
This question uses an interesting approach with DateTime#change to set the tz offset. (Remember that ActiveSupport makes it easy to convert between Time and DateTime.) The downside is that there's no DST detection; you have to do that manually by using TZInfo's current_period.
If given:
2011-10-25 07:21:35 -700
you want:
2011-10-25 07:21:35 UTC
then do:
Time.parse(Time.now.strftime('%Y-%m-%d %H:%M:%S UTC')).to_s
...
>> Time.at(Time.now.utc + Time.zone_offset('PST'))
=> Mon Jun 07 22:46:22 UTC 2010
>> Time.at(Time.now.utc + Time.zone_offset('PDT'))
=> Mon Jun 07 23:46:26 UTC 2010
>> Time.at(Time.now.utc + Time.zone_offset('CST'))
=> Tue Jun 08 00:46:32 UTC 2010
One note: make sure that the current time object is set to UTC time first, otherwise Ruby will try and convert the Time object to your local timezone, thus throwing the calculation. You can always get the adjusted time by applying ".utc" to the end of the above statements in that case.
For those that came across this while looking for a non-rails solution (as I did), TZInfo solved it for me...
require 'tzinfo'
def adjust_time time, time_zone="America/Los_Angeles"
return TZInfo::Timezone.get(time_zone).utc_to_local(time.utc)
end
puts adjust_time(Time.now)
#=> PST or PDT
puts adjust_time(Time.now, "America/New_York")
#=> EST or EDT
This also handles DST, which is what I needed that wasn't handled above.
See: http://tzinfo.rubyforge.org/
in you environment.rb search for the following line.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
Keep in mind ActiveRecord and Rails always handle Time as UTC internally.
I'm using Rails 2.0 before they added the code that makes weppos solution work. Here's what I did
# Silly hack, because sometimes the input_date is in the wrong timezone
temp = input_date.to_time.to_a
temp[8] = true
temp[9] = "Eastern Daylight Time"
input_date = Time.local(*temp)
I break the time down into a 10 element array, change the timezone and then convert the array back into a time.
Here is what worked for me...
def convert_zones(to_zone)
to_zone_time = to_zone.localtime
end
# have your time set as time
time = convert_zones(time)
time.strftime("%b #{day}, %Y (%a) #{hour}:%M %p %Z")
This is what I did, as I am not using Rails and don't want to use any non-core gems.
t = Time.now # my local time - which is GMT
zone_offset = 3600 # offset for CET - which is my target time zone
zone_offset += 3600 if t.dst? # an extra hour offset in summer
time_cet = Time.mktime(t.sec, t.min, t.hour, t.mday, t.mon, t.year, nil, nil, t.dst?, zone_offset)
Option 1
Use date_time_attribute gem:
my_date_time = DateTimeAttribute::Container.new(Time.zone.now)
my_date_time.date_time # => 2001-02-03 22:00:00 KRAT +0700
my_date_time.time_zone = 'Moscow'
my_date_time.date_time # => 2001-02-03 22:00:00 MSK +0400
Option 2
If time is used as an attribute, you can use the same date_time_attribute gem:
class Task
include DateTimeAttribute
date_time_attribute :due_at
end
task = Task.new
task.due_at_time_zone = 'Moscow'
task.due_at # => Mon, 03 Feb 2013 22:00:00 MSK +04:00
task.due_at_time_zone = 'London'
task.due_at # => Mon, 03 Feb 2013 22:00:00 GMT +00:00
It's probably a good idea to store the time as UTC and then show it in a specific time zone when it is displayed. Here's an easy way to do that (works in Rails 4, unsure about earlier versions).
t = Time.now.utc
=> 2016-04-19 20:18:33 UTC
t.in_time_zone("EST")
=> Tue, 19 Apr 2016 15:18:33 EST -05:00
But if you really want to store it in a specific timezone, you can just set the initial Time object to itself.in_time_zone like this:
t = t.in_time_zone("EST")
When Parsing a Time
I'd be interested to hear how you're setting the variable foo to begin with.
If you're parsing a time string that doesn't have a time zone (what I was doing during a data import) then you can use String#in_time_zone to force the time zone during the parsing:
"Fri Jun 26 2019 07:00:00".in_time_zone( "Eastern Time (US & Canada)" )
# => Wed, 26 Jun 2019 07:00:00 EDT -04:00
Works like a charm and is super clean.
You can do:
DateTime.parse('Fri Jun 26 07:00:00 UTC 2009').change(offset: '-0400')
Which returns:
Fri, 26 Jun 2009 07:00:00 -0400