2011-10-29 228 views
1

我经常使用NSDate比较方法 - 但我想考虑两个日期类似的日期,如果它们在年,月,日相等。在比较之前,我已经制作了一个名为“cleanDate”的过程来删除小时部分。比较日期 - 忽略小时部分

-(NSDate*)cleanDate:(NSDate*)date { 
    NSCalendarUnit unitflags; 
    NSDateComponents *component; 
    NSCalendar *calendar; 
    calendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease]; 
    unitflags=NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 
    component=[calendar components:unitflags fromDate:date]; 
    return [calendar dateFromComponents:component]; //Dato uten klokke  
} 

但我的日期出来为:

2011-10-28 22:00:00 和一些日期为:2011-10-28 23:00:00

我希望小时部分相似,例如00:00。

怎么了?它与夏令时有什么关系?其他?谢谢。

+0

例如:OLD 2011-11-01 13:04:33 +0000 新2011-10-31 23:00:00 +0000 似乎成为错误的一天,以及... – folium

回答

0

看起来这是一个时区的问题... 我想的NSLog将默认为本地时区 - 但它似乎默认为GMT ...

Date with GMT time zone is: Sat, 29 Oct 2011 22:00:00 GMT+00:00 
Date with system time zone is: Sun, 30 Oct 2011 00:00:00 GMT+02:00 
NSlog shows 2011-10-29 22:00:00 +0000 

When using NSLog(@"NSlog shows %@",finalDate); it seems to print the GMT time... 
When using this code - I will get the local date in my time zone: 

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss z"]; 
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
NSString *dateString = [dateFormatter stringFromDate:myDate]; 
NSLog(@"Date with system time zone is: %@",dateString); 

...所以我原来的cleanDate实际上似乎做我想要的毕竟...

2
-(NSDate*)cleanDate:(NSDate*)date { 

      NSDateComponents *comps = [[NSCalendar currentCalendar] 
              components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
              fromDate:date]; 
       [comps setHour:0]; 
       [comps setMinute:0];  
       [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]]; 

      return [[NSCalendar currentCalendar] dateFromComponents:comps]; 
} 
+0

谢谢。 OLD 2011-11-01 13:04:33 +0000。新2011-11-01 01:00:00 +0000。我得到正确的一天......第二是好的,分钟是好的......小时是01 ......但只要它固定在01就可以了......这是否如预期的那样? – folium

相关问题