Convert "current time" to "time in minutes since 00:00" calculation help
I do recommend using an NSDate
object to store the time the store closes instead of using your own custom integer format. It's unfortunate that NSDate
represents both date and time of date.
In any case, you can check NSDateComponents
. You can have a utilities method like:
int minutesSinceMidnight:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:date];
return 60 * [components hour] + [components minute];
}
A swift version of what @notnoop has replied:
func minutesSinceMidnight(start : NSDate) -> Int {
let units : NSCalendarUnit = [.Hour, .Minute]
let components = NSCalendar.currentCalendar().components(units, fromDate: start)
return 60 * components.hour + components.minute
}
Swift 5 This for exemple gives you the current number of minutes since midnight
let calendar = Calendar.current
let now = Date()
print(getMinutesSinceMidnight())
func getMinutesSinceMidnight() -> Int {
return (calendar.component(.hour, from: now) * 60 + calendar.component(.minute, from: now))
}