Wrong date comes back from NSDateComponents

一笑奈何 提交于 2019-11-29 18:13:44

Probably the date is correct, but you misunderstood the log:

Logging a date is always done in TZ +0000. For example, if you are in central europe, you will have the (expected?) date 2013-06-28 05:00:00 +0200, but the log will display the normilzed date 2013-06-28 03:00:00 +0000. This is the same date and time! It is simply expressed in a different way.

+++

If your components are in TZ +0000, too, you should set the time zone of the calendar.

You can check whether the current date is between two dates like this:

NSDate *now = [NSDate date];
BOOL betweenStartAndEnd = ([startDate compare:now] == NSOrderedAscending && [endDate compare:now] == NSOrderedDescending);

Your code actually checks whether the tested date is EQUAL (NSOrderedSame) to both start and end dates (which is not of course)

result2 == NSOrderedSame && result1 == NSOrderedSame

See my extended example:

NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components setYear:2013];
[components setMonth:05];
[components setDay:13];
[components setHour:18];
[components setMinute:00];
NSDate *startDate = [myCalendar dateFromComponents:components];
[components setDay:15];
NSDate *endDate = [myCalendar dateFromComponents:components];

NSDate *now = [NSDate date];
BOOL betweenStartAndEnd = ([startDate compare:now] == NSOrderedAscending && [endDate compare:now] == NSOrderedDescending);

NSLog(@"Date %@ %@ between %@ and %@", now, betweenStartAndEnd ? @"IS" : @"IS NOT", startDate, endDate);

This prints out this to the console:

Date 2013-05-13 15:44:06 +0000 IS NOT between 2013-05-13 16:00:00 +0000 and 2013-05-15 16:00:00 +0000

That's because you have to print the date using device's time zone, otherwise it's shown in UTC.

NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
    [components setYear:2013];
    [components setMonth:06];
    [components setDay:28];
    [components setHour:5];
    [components setMinute:00];
    NSDate *startDate1 = [myCalendar dateFromComponents:components];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSLog(@"%@", [formatter stringFromDate:startDate1]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!