1

I found many questions like mine, but I don't understand why it doesn't work.

I have in my Core Data database a list of openings hours. I would like to know if, for a given date, it's opened or closed.

But I don't want check on date. Only on hours, minutes and seconds.

Here the model of my object Opening:

  • NSNumber * days;
  • NSDate * start;
  • NSDate * end;

My problem is I have all the time exactly 42 min and 30 sec more than the original date after extracting time from my NSDate object.

Here my code:

NSCalendar * calendar = [NSCalendar currentCalendar];
NSCalendarUnit flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

for (Opening * opening in openingsForDate) {

    NSDateComponents *date1Components = [calendar components:flags fromDate:date];
    NSDateComponents *date2Components = [calendar components:flags fromDate:opening.start];
    NSDateComponents *date3Components = [calendar components:flags fromDate:opening.end];

    NSDate *date1 = [calendar dateFromComponents:date1Components];
    NSDate *date2 = [calendar dateFromComponents:date2Components];
    NSDate *date3 = [calendar dateFromComponents:date3Components];

    NSLog(@"%@ => %@", date, date1);
    NSLog(@"%@ => %@", opening.start, date2);
    NSLog(@"%@ => %@", opening.end, date3);
}

Here the output:

2017-01-25 22:10:41 +0000 => 0001-01-01 22:53:11 +0000
2017-01-25 11:00:00 +0000 => 0001-01-01 11:42:30 +0000
2017-01-25 22:00:00 +0000 => 0001-01-01 22:42:30 +0000

Any ideas ? Thank you.

EDIT: Solution found here !

Community
  • 1
  • 1
Lapinou
  • 1,467
  • 2
  • 20
  • 39
  • Should I maybe store NSNumber instead of NSDate. So convert hours, minutes and second into NSTimeInterval and store this in my core data database ? However, I don't understand why I have 42 min and 30 seconds more ^^ – Lapinou Jan 25 '17 at 22:26

1 Answers1

0

Instead of converting back to NSDate, just use NSDateComponents hour, minute and second properties to calculate seconds from midnight. Then you can just compare the integers.

NSInteger compareSeconds = date1Components.second + (date1Components.minute*60) + (date1Components.hour*60*60);
NSInteger openingSeconds = date2Components.second + (date2Components.minute*60) + (date2Components.hour*60*60);
NSInteger closingSeconds = date3Components.second + (date3Components.minute*60) + (date3Components.hour*60*60);

if (openingSeconds<compareSeconds && closingSeconds>compareSeconds){
    // Open
} else {
    // Closed
}
markt
  • 903
  • 7
  • 21