Convert Time.zone.now to number OLE - ruby-on-rails

I need convert the DateTime to OLE, Actually I have this code
def self.convert_time(t=42941.6102054745)
Time.at((t - 25569) * 86400).utc
end
but this converts to DateTime now I want this solution :
def self.date_time_ole(dt= Time.zone.now)
# her convert to number ole from datetime
end
could you please help me ?

Ruby's Date class subtraction returns number of days between 2 dates, so you just need to subtract your "custom epoch" (December 30, 1899 at midnight) from the other date:
ole_epoch = DateTime.new(1899, 12, 30, 0, 0, 0)
now = DateTime.now # => 2017-08-18 21:03:28 UTC
(now - ole_epoch).to_f # => 42965.87741847492
and that should be OLE and you can also just add it to go the other way:
ole_epoch + 42965.87741847492 # => Fri, 18 Aug 2017 21:03:28 +0000

Related

How to retrieve data in database with UTC datetime

I need to fetch a data in our database as a report using Ruby on Rails but I have a problem with the date-time ex:
This order was made on:
but on our database it's dated plus 8hours because we saved it as UTC:
Then I have a query:
Spree::Order
.joins(user:[:corporate_account])
.includes(line_items:[:variant])
.where('spree_orders.completed_at IS NOT NULL')
.ransack(#params[:q])
start_date and end_date are converted into:
#params[:q][start_date] = params[:q][start_date].to_datetime.beginning_of_day
#params[:q][end_date] = params[:q][end_date].to_datetime.end_of_day
to get the orders starting at 12:00 am til 11:59:59 pm end of day.
I am not allowed to change how we saved the date-time in our database and we can't make a cut-off.
I can't also add 1 day at end of the day because the orders will have a discrepancy.
I also tried converting PST to UTC doesn't work because let's say I want to generate a report at 5 pm right now with a date of 2021/12/01, I have to convert it to end of the day so that's 2021/12/01 11:59:59 it won't include the orders made at 5 pm 2021/12/01 since it'll be offset on the database with 8hrs, it'll be saved as 2021/12/02 1am
So my question is how would you query a data with such date-time offset?
You could try something like this:
timezone = "Pacific Time (US & Canada)"
start_date = Date.parse(#params[:q][:start_date])
end_date = Date.parse(#params[:q][:end_date])
#params[:q][:start_date] = Time.find_zone(timezone).local(start_date.year, start_date.month, start_date.day, 0, 0, 0)
#params[:q][:end_date] = Time.find_zone(timezone).local(end_date.year, end_date.month, end_date.day, 23, 59, 59)
For example:
timezone = "Pacific Time (US & Canada)"
start_date = Date.parse("2021-11-30")
end_date = Date.parse("2021-11-30")
#params[:q][:start_date] = Time.find_zone(timezone).local(2021, 11, 30, 0, 0, 0) # => Tue, 30 Nov 2021 00:00:00.000000000 PST -08:00
#params[:q][:start_date].utc # 2021-11-30 08:00:00 UTC
#params[:q][:end_date] = Time.find_zone(timezone).local(2021, 11, 30, 23, 59, 59) # Tue, 30 Nov 2021 23:59:59.000000000 PST -08:00
#params[:q][:end_date].utc # 2021-12-01 07:59:59 UTC

Formatting Date in Rails

How can I format this datetime attribute 2017-10-15 or how can I get the 15th of the current month?
#today = Time.now
#mid = time.strftime("%Y-%m-15")
into October 15, 2017? I tried using to_formatted_s(:long), but it gives an error of undefined method.
In Rails 4 or above
> Date.today.beginning_of_month + 14
#=> Sun, 15 Oct 2017
# formatted as per your requirement
> (Date.today.beginning_of_month + 14).strftime("%B %d, %Y")
#=> "October 15, 2017"
Date#beginning_of_month it will return you beginning date of month of specified date (which will be always 1st, add 14 days) so you will get 15th of that month
Mydate = "2017-10-15"
Mydate.to_date.strftime("%B %d, %Y")
=> "October 15, 2017"
Using #GaganGami solution, you can create a Date class method middle_of_current_month
class Date
def self.middle_of_current_month
(today.beginning_of_month + 14).strftime("%B %d, %Y")
end
end
Date.middle_of_current_month
#=> "October 15, 2017"

Ruby / Rails - Change the timezone of a Time, without changing the value

I have a record foo in the database which has :start_time and :timezone attributes.
The :start_time is a Time in UTC - 2001-01-01 14:20:00, for example.
The :timezone is a string - America/New_York, for example.
I want to create a new Time object with the value of :start_time but whose timezone is specified by :timezone. I do not want to load the :start_time and then convert to :timezone, because Rails will be clever and update the time from UTC to be consistent with that timezone.
Currently,
t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t.in_time_zone("America/New_York")
=> Sat, 01 Jan 2000 09:20:00 EST -05:00
Instead, I want to see
=> Sat, 01 Jan 2000 14:20:00 EST -05:00
ie. I want to do:
t
=> 2000-01-01 14:20:00 UTC
t.zone = "America/New_York"
=> "America/New_York"
t
=> 2000-01-01 14:20:00 EST
Sounds like you want something along the lines of
ActiveSupport::TimeZone.new('America/New_York').local_to_utc(t)
This says convert this local time (using the zone) to utc. If you have Time.zone set then you can of course to
Time.zone.local_to_utc(t)
This won't use the timezone attached to t - it assumes that it's local to the time zone you are converting from.
One edge case to guard against here is DST transitions: the local time you specify may not exist or may be ambiguous.
I've just faced the same problem and here is what I'm going to do:
t = t.asctime.in_time_zone("America/New_York")
Here is the documentation on asctime
If you're using Rails, here is another method along the lines of Eric Walsh's answer:
def set_in_timezone(time, zone)
Time.use_zone(zone) { time.to_datetime.change(offset: Time.zone.now.strftime("%z")) }
end
You need to add the time offset to your time after you convert it.
The easiest way to do this is:
t = Foo.start_time.in_time_zone("America/New_York")
t -= t.utc_offset
I am not sure why you would want to do this, though it is probably best to actually work with times the way they are built. I guess some background on why you need to shift time and timezones would be helpful.
Actually, I think you need to subtract the offset after you convert it, as in:
1.9.3p194 :042 > utc_time = Time.now.utc
=> 2013-05-29 16:37:36 UTC
1.9.3p194 :043 > local_time = utc_time.in_time_zone('America/New_York')
=> Wed, 29 May 2013 12:37:36 EDT -04:00
1.9.3p194 :044 > desired_time = local_time-local_time.utc_offset
=> Wed, 29 May 2013 16:37:36 EDT -04:00
Depends on where you are going to use this Time.
When your time is an attribute
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
When you set a separate variable
Use the same 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
Here's another version that worked better for me than the current answers:
now = Time.now
# => 2020-04-15 12:07:10 +0200
now.strftime("%F %T.%N").in_time_zone("Europe/London")
# => Wed, 15 Apr 2020 12:07:10 BST +01:00
It carries over nanoseconds using "%N". If you desire another precision, see this strftime reference.
The question's about Rails but it seems, like me, not everyone here is on the ActiveSupport train, so yet another option:
irb(main):001:0> require "time"
=> true
irb(main):003:0> require "tzinfo"
=> true
irb(main):004:0> t = Time.parse("2000-01-01 14:20:00 UTC")
=> 2000-01-01 14:20:00 UTC
irb(main):005:0> tz = TZInfo::Timezone.get("America/New_York")
=> #<TZInfo::DataTimezone: America/New_York>
irb(main):008:0> utc = tz.local_to_utc(t)
=> 2000-01-01 19:20:00 UTC
irb(main):009:0> tz.utc_to_local(utc)
=> 2000-01-01 14:20:00 -0500
irb(main):010:0>
local_to_utc not doing the opposite of utc_to_local might look like a bug but it is at least documented: https://github.com/tzinfo/tzinfo says:
The offset of the time is ignored - it is treated as if it were a local time for the time zone
I managed to do this by calling change with the desired time zone:
>> t = Time.current.in_time_zone('America/New_York')
=> Mon, 08 Aug 2022 12:04:36.934007000 EDT -04:00
>> t.change(zone: 'Etc/UTC')
=> Mon, 08 Aug 2022 12:04:36.934007000 UTC +00:00
https://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-change
def relative_time_in_time_zone(time, zone)
DateTime.parse(time.strftime("%d %b %Y %H:%M:%S #{time.in_time_zone(zone).formatted_offset}"))
end
Quick little function I came up with to solve the job. If someone has a more efficient way of doing this please post it!
I spent significant time struggling with TimeZones as well, and after tinkering with Ruby 1.9.3 realized that you don't need to convert to a named timezone symbol before converting:
my_time = Time.now
west_coast_time = my_time.in_time_zone(-8) # Pacific Standard Time
east_coast_time = my_time.in_time_zone(-5) # Eastern Standard Time
What this implies is that you can focus on getting the appropriate time setup first in the region you want, the way you would think about it (at least in my head I partition it this way), and then convert at the end to the zone you want to verify your business logic with.
This also works for Ruby 2.3.1.
I have created few helper methods one of which just does the same thing as is asked by the original author of the post at Ruby / Rails - Change the timezone of a Time, without changing the value.
Also I have documented few peculiarities I observed and also these helpers contains methods to completely ignore automatic day-light savings applicable while time-conversions which is not available out-of-the-box in Rails framework:
def utc_offset_of_given_time(time, ignore_dst: false)
# Correcting the utc_offset below
utc_offset = time.utc_offset
if !!ignore_dst && time.dst?
utc_offset_ignoring_dst = utc_offset - 3600 # 3600 seconds = 1 hour
utc_offset = utc_offset_ignoring_dst
end
utc_offset
end
def utc_offset_of_given_time_ignoring_dst(time)
utc_offset_of_given_time(time, ignore_dst: true)
end
def change_offset_in_given_time_to_given_utc_offset(time, utc_offset)
formatted_utc_offset = ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, false)
# change method accepts :offset option only on DateTime instances.
# and also offset option works only when given formatted utc_offset
# like -0500. If giving it number of seconds like -18000 it is not
# taken into account. This is not mentioned clearly in the documentation
# , though.
# Hence the conversion to DateTime instance first using to_datetime.
datetime_with_changed_offset = time.to_datetime.change(offset: formatted_utc_offset)
Time.parse(datetime_with_changed_offset.to_s)
end
def ignore_dst_in_given_time(time)
return time unless time.dst?
utc_offset = time.utc_offset
if utc_offset < 0
dst_ignored_time = time - 1.hour
elsif utc_offset > 0
dst_ignored_time = time + 1.hour
end
utc_offset_ignoring_dst = utc_offset_of_given_time_ignoring_dst(time)
dst_ignored_time_with_corrected_offset =
change_offset_in_given_time_to_given_utc_offset(dst_ignored_time, utc_offset_ignoring_dst)
# A special case for time in timezones observing DST and which are
# ahead of UTC. For e.g. Tehran city whose timezone is Iran Standard Time
# and which observes DST and which is UTC +03:30. But when DST is active
# it becomes UTC +04:30. Thus when a IRDT (Iran Daylight Saving Time)
# is given to this method say '05-04-2016 4:00pm' then this will convert
# it to '05-04-2016 5:00pm' and update its offset to +0330 which is incorrect.
# The updated UTC offset is correct but the hour should retain as 4.
if utc_offset > 0
dst_ignored_time_with_corrected_offset -= 1.hour
end
dst_ignored_time_with_corrected_offset
end
Examples which can be tried on rails console or a ruby script after wrapping the above methods in a class or module:
dd1 = '05-04-2016 4:00pm'
dd2 = '07-11-2016 4:00pm'
utc_zone = ActiveSupport::TimeZone['UTC']
est_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
tehran_zone = ActiveSupport::TimeZone['Tehran']
utc_dd1 = utc_zone.parse(dd1)
est_dd1 = est_zone.parse(dd1)
tehran_dd1 = tehran_zone.parse(dd1)
utc_dd1.dst?
est_dd1.dst?
tehran_dd1.dst?
ignore_dst = true
utc_to_est_time = utc_dd1.in_time_zone(est_zone.name)
if utc_to_est_time.dst? && !!ignore_dst
utc_to_est_time = ignore_dst_in_given_time(utc_to_est_time)
end
puts utc_to_est_time
Hope this helps.
This worked well for me
date = '23/11/2020'
time = '08:00'
h, m = time.split(':')
timezone = 'Europe/London'
date.to_datetime.in_time_zone(timezone).change(hour: h, min: m)
This changes the timezone to 'EST' without changing the time:
time = DateTime.current
Time.find_zone("EST").local(
time.year,
time.month,
time.day,
time.hour,
time.min,
time.sec,
)

How do I force a Time in utc when server is in another timezone

My server has system timezone "Europe/Paris"
I configured my Rails app ( Rails 3.29)
config.time_zone = 'Europe/London'
config.active_record.default_timezone = :utc
all event start/end dates are the stored in db as : "2013-01-02 10:00:00"
the issue is on scoping
scope :starting, lambda {|start_date_time|
{:conditions => ["starts_at = ?", Event.db_datetime(start_date_time)] }
}
...
def self.db_datetime(date_time)
Time.at(date_time.to_i).utc.to_s(:db)
end
when I create start_date_time filter ,
I get a system local time-zoned datetime
start_date_time = Time.new(2013, 1, 2, 10, 0, 0)
2013-01-02 10:00:00 +0100
and Event.db_datetime(start_date_time) gives "2013-01-02 09:00:00"
which cannot be found
Is there a way to force utc datetime so :
start_date_time = Time.new(2013, 1, 2, 10, 0, 0) would give
2013-01-02 10:00:00 UTC
thanks for feedback
Time.at - or Time.new - parses the time in the system local time zone, which here appears to be UTC+1.
That's why parsing 10:00 in UTC+1 becomes 09:00 in UTC.
I think the function you are looking for is
Time.zone.at #equivalent to Time.at
Time.zone.local(2013, 1, 2, 10, 0, 0) #equivalent to Time.new
which will parse the given date and time in the time zone defined by
config.time_zone = 'Europe/London'
The result of this is a TimeWithZone object, which is a Rails extention to the ruby Time.
You can check this documentation page http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html for more informations about TimeWithZone.
You can use it this way; the db_datetime(date_time) method is not really necessary anymore :
# class Event
scope :starting, lambda {|start_date_time|
{:conditions => ["starts_at = ?", start_date_time.to_s(:db)] }
}
# I think to_s(:db) already handle the .utc conversion part
## example
start_date_time = Time.zone.local(2013, 1, 2, 10, 0, 0)
Event.starting(start_date_time)

How do I calculate the next annual occurrence of a date?

Given a Ruby date, does a one liner exist for calculating the next anniversary of that date?
For example, if the date is May 01, 2011 the next anniversary would be May 01, 2012, however if it is December 01, 2011, the next anniversary is December 01, 2011 (as that date hasn't yet arrived).
If you date variable is an instance of Date then you can use >>:
Return a new Date object that is n months later than the current one.
So you could do this:
one_year_later = date >> 12
The same approach applies to DateTime. If all you have is a string, then you can use the parse method:
next_year = Date.parse('May 01, 2011') >> 12
next_year_string = (Date.parse('May 01, 2011') >> 12).to_s
IMHO you're better off using the date libraries (Date and DateTime) as much as possible but you can use the Rails extensions (such as 1.year) if you know that Rails will always be around or you don't mind manually pulling in active_support as needed.
An excellent gem exists for doing this called recurrence. You can checkout the source code or some samples:
https://github.com/fnando/recurrence
http://blog.plataformatec.com.br/tag/recurrence/
For example, if you have a date set you could try:
date = ...
recurrence = Recurrence.new(every: :year, on: [date.month, date.day])
puts recurrence.next
You can do it using Ruby's Date class:
the_date = Date.parse('jan 1, 2011')
(the_date < Date.today) ? the_date + 365 : the_date # => Sun, 01 Jan 2012
the_date = Date.parse('dec 31, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sat, 31 Dec 2011
Or, for convenience use ActiveSupport's Date class extensions:
require 'active_support/core_ext/date/calculations'
the_date = Date.parse('jan 1, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sun, 01 Jan 2012
the_date = Date.parse('dec 31, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sat, 31 Dec 2011
Try this:
def next_anniversary(d)
Date.today > d ? 1.year.from_now(d) : d
end
Pulling in a gem just to do this is overkill.
your_date > Date.today ? your_date : your_date >> 12

Resources