Im trying to calculate the time difference between 18:00 & 06:00 and display the result in the same format. Both times are entered manually.
Asked
Active
Viewed 682 times
0
-
can you show us the code you've tried? – Steve May 02 '16 at 17:23
-
this may help http://stackoverflow.com/questions/24316521/time-comparisons-in-swift – Steve May 02 '16 at 17:26
-
Hi Steve the times art NSDate they are entered manually. – Marcus Romer May 02 '16 at 18:00
-
you can create an NSDate from your input strings and then do the compare. – Steve May 02 '16 at 18:01
1 Answers
1
First create two NSDates from the string inputs and get the interval between the two then pass the interval through a formatting function we will create:
let date1:String = "12:00"
let date2:String = "13:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date3 = dateFormatter.dateFromString(date1)
let date4 = dateFormatter.dateFromString(date2)
let interval = date4!.timeIntervalSinceDate(date3!)
print("\(stringFromTimeInterval(interval))")
now we need to format the interval which is the number of seconds between the two so create a function which returns a string:
func stringFromTimeInterval(interval: NSTimeInterval) -> String {
let interval = Int(interval)
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
return String(format: "%02d:%02d", hours, minutes)
}
in your case you will set the date1 and date2 from I'm guessing the text fields in your program.

Steve
- 1,371
- 9
- 13
-
-
How do I save the data i.e. time difference, once displayed, I am now using NSDate format. – Marcus Romer May 03 '16 at 12:59
-
how would you like to save it? are you on a mac or iOS device? is this the only number you are saving? This is a big discussion there are many ways. If you are just saving a single number and are on an iOS device do a google search for NSUserDefaults. – Steve May 03 '16 at 13:15
-
My ambition is to build a time sheet, saving start time, finish time less breaks. I have every thing laid out and having issues saving the time difference. On iOS device. – Marcus Romer May 03 '16 at 13:36
-
is this for one device or multiple devices to the same place? it sounds to me you want this for multiple users to the same place. If that is the case look into backend services like firebase or backand – Steve May 03 '16 at 13:43
-
Im using it for personal use so theres no need for multiple device settings. – Marcus Romer May 03 '16 at 13:45
-