Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "current time" to "time in minutes since 00:00" calculation help

I haven't used NSDate that much, so I'd like some help with a calculation I am doing.

I have an integer that has my store's closing hour in minutes since midnight. Basically, my store closes at 5.00PM, which gives me the integer 1020.

So right now it's 10.45PM or 22.45. Integer since 00:00 is 1365, and from this I can say

if (storeHour < currentTime) {
      // closed!
}

However, I don't know how I get from "22.45" that I have from NSDate to converting it to an integer representing time since 00:00. Is there something in NSDate that can help me with that?

Thx

like image 612
runmad Avatar asked Nov 30 '09 03:11

runmad


2 Answers

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];    
}
like image 153
notnoop Avatar answered Oct 11 '22 12:10

notnoop


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))
 }
like image 42
glemoulant Avatar answered Oct 11 '22 12:10

glemoulant