Trying to use NSDate for time only

Noam Solovechick picture Noam Solovechick · May 4, 2013 · Viewed 8.4k times · Source

I'm struggling to find a way to use NSDate for time only purposes. I was trying to do the following code:

- (void)awakeFromInsert
{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps.minute = 45;
    comps.second = 0;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    self.periodDuration = [calendar dateFromComponents:comps];
    NSLog(@"periodDuration: %@",self.periodDuration);

    comps = [[NSDateComponents alloc] init];
    comps.hour = 8;
    comps.minute = 0;
    self.firstPeriodStartTime = [calendar dateFromComponents:comps];
    NSLog(@"firstPeriodTime: %@",self.periodDuration);
}

But the result I get is:

periodDuration: 0001-12-31 22:24:04 +0000
firstPeriodTime: 0001-12-31 22:24:04 +0000

The result I was expecting:

periodDuration: 45:00
firstPeriodTime: 08:00

What am I doing wrong? How can I fix this? Thank you.

Answer

Anupdas picture Anupdas · May 4, 2013

The log of date is misleading you, if you are forming a date with only a few components you will not get a proper date instance which uniquely identifies a date and time.

If you try with this code snipped you can find that if you are just converting the dates back to string it is just as you expect

NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *periodDate = [calendar dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
NSLog(@"periodDuration: %@",[dateFormatter stringFromDate:periodDate]);

comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
NSDate *firstPeriodDate = [calendar dateFromComponents:comps];
[dateFormatter setDateFormat:@"HH:mm"];
NSLog(@"firstPeriodTime: %@",[dateFormatter stringFromDate:firstPeriodDate]);

periodDuration: 45:00

firstPeriodTime: 08:00