In Rails, how to convert time zone into an integer - ruby-on-rails

I have time and time zone, what I need is I just want to convert like this Wed, 11 Dec 2019 19:00:00 +0530 and then I need to convert like this 1576071000.
So for I tried like this
time = "19"
hour = "00"
time_zone = "IST"
e = DateTime.now.change({hour: time, minute: hour})
I get the exact output, but I need to convert with timezone. that means something like this
DateTime.now.change({hour: time, minute: hour}).time_zone('IST')

credit to #engineersmnky
hour = 19
minute = 0
time_zone = 'Chennai'
e = Time.zone.now.change({hour: hour, minute: minute}).in_time_zone(time_zone).to_i

You need to convert it to UTC:
DateTime.now.change({hour: time, minute: hour}).time_zone('IST').utc
Or if you are in Rails 4 or above you can use in_time_zone:
DateTime.now.change({hour: time, minute: hour}).in_time_zone('IST').utc

Related

Ruby on rails get hours, minutes, seconds from two dates and times

I need the number of hours, minutes, seconds between two dates and times.I'm able to get the number of days, hours, minutes, seconds but I don't want no.of days instead of it, I need hours, minutes, seconds only enough.
Here my code,
start_time is Wed, 13 Dec 2017 20:35:19 -0800 and end_time is today datetime
def time_diff(end_time, start_time)
diff = end_time - start_time
mm, ss = diff.divmod(60)
hh, mm = mm.divmod(60)
dd, hh = hh.divmod(24)
time = "%d h, %d m, %d s" % [hh, mm, ss]
return time
end
I need output like this "35 h, 29 m, 12 s"
Thanks for your help.
Just out of curiosity, a pure [almost] functional solution, without intermediate local variables:
start_time = DateTime.parse 'Wed, 13 Dec 2017 23:00:00 UTC'
end_time = DateTime.parse 'Wed, 15 Dec 2017 23:30:20 UTC'
sec, min, hrs = [60, 60, 1].
map.
with_object([[[end_time, start_time].
map(&:to_time).
map(&:to_i).
reduce(:-), nil]]) do |div, obj|
obj << obj.last.first.divmod(div)
obj[-2].rotate!
end.
map(&:first).
compact
#⇒ [20, 30, 48]
You've already got the answer - just don't divide by 24!
If the start_time and end_time are DateTime value you can use the following
difference = end_time - start_time
hours = (difference * 24).to_i
minutes = (difference * 24 * 60).to_i
seconds = (difference * 24 * 60 * 60).to_i

Swift - Timezone off by one hour / secondsFromGMT incorrect

This should be a really simple question but I just can't seem to wrap my head around it.
Given my timezone is EDT (GMT-4), why does 04:00 in GMT turn into 23:00 and not 00:00?
// The offset is -4 hours
let offsetFromGMT = Calendar.current.timeZone.secondsFromGMT() / 60 / 60
// 2017-03-12 04:00
var destinationComponents = DateComponents()
destinationComponents.timeZone = TimeZone(secondsFromGMT: 0)
destinationComponents.year = 2017
destinationComponents.month = 03
destinationComponents.day = 12
destinationComponents.hour = -offsetFromGMT // 4 hours
// Why is this 2017-03-11 23:00 and not 2017-03-12 00:00?
let date = Calendar.current.date(from: destinationComponents)!
// Outputs 23
Calendar.current.dateComponents([.hour], from: date).hour
Calendar.current.timeZone.secondsFromGMT()
is the current GMT offset for your time zone. In your case that
is 4 hours, because the current time zone in New York is EDT = GMT-4,
with daylight saving time active.
So your destinationComponents and date are four o'clock in
the morning Greenwich time:
2017-03-12 04:00:00 +0000
At that point, the time zone in New York was EST = GMT-5, and
daylight saving time not active. Therefore that date is 2017-03-11 23:00 in your local time zone.
I would proceed differently, avoiding "secondsFromGMT".
Example: "2017-03-12 00:00:00" New York time is "2017-03-12 05:00:00" GMT.
var srcComponents = DateComponents()
srcComponents.timeZone = TimeZone(identifier: "America/New_York")!
srcComponents.year = 2017
srcComponents.month = 3
srcComponents.day = 12
srcComponents.hour = 0
srcComponents.minute = 0
let date = Calendar.current.date(from: srcComponents)!
print(date) // 2017-03-12 05:00:00 +0000

NSComparisonResult is not working as expected for 10 PM and above

I need to compare two times in Swift and using NSComparisonResult I could get correct result until it comes to time between 10 PM - 11:59 PM. It shows opposite result for these times. Anyone know what's the issue with this? Below is sample code and scenario's. 10:30:00 PM is example time to test, but you can test it with any time.
// For test, Current time 10:30:00 PM
let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .LongStyle)
let closeTimeCompareResult: NSComparisonResult = currentTime.compare("10:00:00 PM EDT")
print("DinnerClose: \(closeTimeCompareResult.rawValue)")
// Expected result is -1 but, getting as 1
// It works perfect until 9:59:59 PM
let closeTimeCompareResult9: NSComparisonResult = currentTime.compare("9:00:00 PM EDT")
print("DinnerClose: \(closeTimeCompareResult9.rawValue)")
// As expected result is -1
You're performing a string comparison. So you're comparing these two strings, for example:
10:00:00 PM EDT
9:00:00 PM EDT
A string comparison compares the corresponding characters of each string, starting with the first character of each. The first character of "10:00:00 PM EDT" is "1" and the first character of "9:00:00 PM EDT" is "9". In Unicode and ASCII, "9" is code point 57 and "1" is code point 49. Since 57 > 49, "9" > "1", and "9:00:00 PM EDT" > "10:00:00 PM EDT".
You probably want to extract the hour, minute, and second from the input date, and then compare them numerically. If you've upgraded to Xcode 7.3 with Swift 2.2, then you can use a tuple comparison like this:
let date = NSDate()
let components = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: date)
let hms = (components.hour, components.minute, components.second)
if hms >= (21, 0, 0) && hms < (22, 30, 0) {
print("\(date) is between 9 PM and 10:30 PM in the system's time zone.")
}

How to get year month day from NSDate for the current timezone

I am current at timezone UTC-05:00. When I call the function NSDate(timeIntervalSince1970:0), it returns back "Dec 31, 1969, 7:00 PM"
let date = NSDate.init(timeIntervalSince1970: 0) // "Dec 31, 1969, 7:00 PM"
print(date) // "1970-01-01 00:00:00 +0000\n"
I read about this How to get NSDate day, month and year in integer format? But the problem is that with the following, I always get 1969-12-31 because of the 5 hour time difference.
let calendar = NSCalendar.currentCalendar()
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date)
year // 1969
month // 12
day // 31
var hour = 0, minute = 0, second = 0
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: nil, fromDate: date)
hour // 19
minute // 0
second // 0
Is there a way to get the current year, month, day values and etc. in the current timezone. What I am looking for here is:
year // 1970
month // 01
day // 01
The timeIntervalSince1970 initializer gives you (as documented) an NSDate which is some number of seconds since Jan 1 1970 at 00:00:00 in UTC, not in your local time zone. Those results you're getting are correct, because they're showing your local time zone's offset from that time. You're passing in 0, so you're getting Jan 1 1970 at 00:00:00 UTC, and then NSCalendar is giving you the equivalent date and time in your local time zone.
If you want to get Jan 1 1970 at 00:00:00 in your local time zone, you need to request that date specifically from NSCalendar:
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.localTimeZone()
let date = calendar.dateWithEra(1, year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date!)
year // 1970
month // 1
day // 1
This is not a 0 offset for timeIntervalSince1970. If you check, you'll see that the result corresponds to your time zone's offset from UTC:
date?.timeIntervalSince1970 // 25200, for me
This will return the current date ex. 02/26/2016
// Format date so we may read it normally
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/M/yyyy"
let currentDate = String(dateFormatter.stringFromDate(NSDate()))
Swift 3.0
NSDateFormatter > DateFormatter && NSDate > Date
let df = DateFormatter()
df.timeZone = .current
df.dateStyle = .medium
df.timeStyle = .short
df.dateFormat = "dd/M/yyyy"
let currentDate = df.string(from: Date())

Transforming date + time in a TimeStamp Object

I'm having some trouble with making a timestamp from a date and a time
What i'm trying to do:
date = "2016 2 21"
time = "03:00 UTC"
output = "Thu, 21 Feb 2016 03:00:00 UTC +00:00"
I'm getting the date from a form_for:
f.date_field(:date_first)
But I'm not sure of how should I pick up the time.
To give you a headstart:
dt = "2016-2-21"
time = "03:00 UTC"
dtime = DateTime.parse(dt + 'T' + time)
output = dtime.rfc2822
and the result is:
#=> "Sun, 21 Feb 2016 03:00:00 +0000"
Maybe you could do something like this
strftime("%d.%m.%Y. %H:%M:%S")
and also get your locale yml file from here
https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale

Resources