How to format time durations in Groovy? - parsing

I need to show time elapsed. I have the dates in following format.
Date1 = Thu May 23 10:10:10 EDT 2013
Date2 = Tue May 21 10:10:10 EDT 2013
I currently did TimeDuration duration=TimeCategory.minus(now,LaunchTime)
And my output shows something like 2 days, 23 minutes, 25.154 seconds
What I want to show instead of 2 days, 23 minutes, 25.154 seconds is something like 48:23:25(in hours and minutes).

You can do something like this to create a new TimeDuration with the days turned into hours:
import groovy.time.TimeDuration
import groovy.time.TimeCategory
date1 = Date.parseToStringDate( 'Thu May 23 10:10:10 EDT 2013' )
date2 = Date.parseToStringDate( 'Tue May 21 12:14:10 EDT 2013' )
// Normalize method to return a new TimeDuration
TimeDuration normalize( TimeDuration tc ) {
new TimeDuration( ( tc.days != 0 ? tc.days * 24 : 0 ) + tc.hours,
tc.minutes, tc.seconds, tc.millis )
}
// Then use the category to subtract the dates, and call normalize
TimeDuration normalized = use( groovy.time.TimeCategory ) {
normalize( date1 - date2 )
}
println normalized

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 query by date offset in Parse with Swift?

I want to set a constraint on a Parse query, that takes a birthday ( date), and only gathers results which are within 10 years.
So if the date is something like (1954-01-10 07:00:00 +0000)
then I want to get all records from 1944 to 1964.
Is there some way to do this using Parse query code?
Or,
do I have to obtain the date, then use swift code to offset it by 10 years, then write something like this
let currentUserBirthday = PFUser.currentUser()?.objectForKey("birthday")!
// set date 10 years greater and lower than currentUserBirthday
let datePlus10 = // add 10 years to date
let dateMinus10 = // subtract 10 years from date
dailyFourQuery?.whereKey("birthday", greaterThanOrEqualTo: datePlus10)
dailyFourQuery?.whereKey("birthday", lessThanOrEqualTo: dateMinus10)
edit: hey guys, i solved this by getting the age from the date, then adding or subtracting the integer offset from that number,
then using NSCalendar and creating components with modified values.
Thanks for all the help.
let currentUserBirthdayNSDate = currentUserBirthday as! NSDate
let dateComponents = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second, NSCalendarUnit.Nanosecond], fromDate: currentUserBirthdayNSDate)
let componentsPlus10 = NSDateComponents()
componentsPlus10.day = dateComponents.day
componentsPlus10.month = dateComponents.month
componentsPlus10.year = dateComponents.year + 10
componentsPlus10.hour = dateComponents.hour
componentsPlus10.minute = dateComponents.minute
You can refer to SwiftDate
// Reference date is: Thu, 19 Nov 2015 19:00:00 UTC (1447959600 from 1970)
let refDate = NSDate(timeIntervalSince1970: 1447959600)
// Remember: all parameters are optional; in this example we have ignored minutes and seconds
let newDate = refDate.add(years: 1, months: 2, days: 1, hours: 2)
// newdate is 2017-01-21 14:00:00 +0000
// This is equivalent to
let newDate2 = refDate + 1.years + 2.months + 1.days + 2.hours
do you want this?

Subtracting Time.now from End_time (UTC) gives me a float (hhmmss.xx). How do I format it to HH:MM so that I can use it for a countdown timer?

I have an end_time that I would like to create a timer for end_time.utc - Time.now. However, when I subtract the value, I get a float like 23510.29642 which I found to represent hours, minutes,seconds followed by a period and milliseconds.
end_time
=> Wed, 04 Jun 2014 19:00:00 UTC +00:00
end_time.utc - Time.now
=> -24614.329399
How do I format the float so that I get -2:46 without manually parsing the string?
Difference between two Time objects returns number of seconds between two times.
e = Time.parse("Wed, 04 Jun 2014 19:00:00 UTC +00:00")
diff = e - Time.parse("Wed, 04 Jun 2014 21:49:00 UTC +00:00")
hours = (diff / 3600).to_i
minutes = (diff / 60).to_i % 60 # if e < Time.now then minutes = (diff / 60).to_i % 60 - 60
seconds = diff.to_i % 60 # same as minutes
puts hours # -2
puts minutes # -49
puts seconds # 0

Resources