Reputation: 2199
While querying data from a database I receive the hours a process is started and ended in two separate string fields for example start = "1100" and end = "+0200" which indicate it's hours of operation are from 11am-2am. What is the proper way to represent this in swift so that I can determine the amount of time left from the current time to the end time of the process.
EDIT: I found an interesting way using the date formatter if I remove any possible prefix of + and use the below code it seems to work correctly; however, the date is not set is their a work around?
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HHmm"
let date = dateFormatter.dateFromString("1340")
Upvotes: 0
Views: 926
Reputation: 11555
You can create NSDate
from components using NSCalendar.currentCalendar().dateWithEra
(there are other similar functions, look up NSCalendar
for details). You will need to add some logic to determine if the 2AM is today or tomorrow etc.
Then you can compare two NSDate
dates. To determine time left to the end you would probably use NSDate
method timeIntervalSinceDate
. You can also use NSDateComponentsFormatter
to get the remaining time nicely formatted.
Upvotes: 2