Reputation: 1736
I would like that my app would show how much time has passed since some time mark, like Stopwatch. Should I used NSdate?
I've tried using NSDate(timeIntervalSinceReferenceDate:_)
and as parameter I wanted to chose NSDate(timeIntervalSince1970: someTimeStamp)
which is not allowed.
I also tried doing it manually, by converting NSTimeInterval
of current time to Int
like this:
var date = NSDate().timeIntervalSince1970
let time3 = Int(date)
let time4 = Int(someTimeStamp) //NSTimeInterval in Epoch time
let time5 = Double(time3 - time4)
let time6 = NSDate(timeIntervalSinceReferenceDate: time5) //This is what I need
Although now I am not sure how to properly display time6
, I could do manually divide by 60 to get minutes and divide by 60 to get hours, but I am pretty sure there has to be simpler way to display how much time has passed since NSTimeInterval
(preferably in mm
format if below 60 minutes and in hh:mm
if above 60 minutes)
Upvotes: 1
Views: 2872
Reputation: 195
Thank you @Bhavuk, here's what I came up with for Swift 4
let now = Date()
let yesterday = Date.init(timeIntervalSinceNow: -86400)
let calendar = Calendar.current
let componentSet: Set = [Calendar.Component.hour, .minute, .second]
let components = calendar.dateComponents(componentSet, from: now, to: yesterday)
let seconds = components.second!
let minutes = components.minute!
let hours = components.hour!
print("Seconds: \(seconds), Minutes:\(minutes), Hours:\(hours)")
Upvotes: 1
Reputation: 2187
You can use this: (Objective C)
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSSecondCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:apptDt
toDate:deliveredDt options:0];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
NSInteger hours = [components hour];
Swift:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let unitFlags:NSCalendarUnit = NSCalendarUnit.Hour.union(NSCalendarUnit.Minute).union(NSCalendarUnit.Second)
let components = gregorian?.components(unitFlags, fromDate: apptDt, toDate:deliveredDt, options: .MatchFirst)
let seconds = components?.second
let minute = components?.minute
let hour = components?.hour
print("Second: \(seconds), Minutes:\(minute), Hour:\(hour)")
Just put starting date in 'fromDate' and 'toDate' current date.
Upvotes: 1
Reputation: 2423
let elapsedTime = NSDate().timeIntervalSinceDate(DateYouWantToPassToGetInterval)
Note the () after the NSDate. The NSDate() instantiates a new NSDate object, and then timeIntervalSinceDate returns the time difference between that and timeAtPress. That will return a floating point value (technically, a NSTimeInterval).
If you want that as truncated to an Int value, you can just use:
let duration = Int(elapsedTime)
Upvotes: 1