比较日期-忽略小时部分 [英] Compare dates - overlooking the hour part

查看:48
本文介绍了比较日期-忽略小时部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用NSDate比较方法-但如果年,月,日中的两个日期相等,我想考虑两个日期相似.我进行了一个名为"cleanDate"的操作,以在比较之前删除小时部分.

I frequently use the NSDate compare method - but I want to consider two dates similar if they are equal in year, month, day. I have made a procesure called "cleanDate" to remove the hour part before I compare.

-(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

2011-10-28 22:00:00 and some dates as: 2011-10-28 23:00:00

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

I want the hour part to be similar, e.g. 00:00.

怎么了?它与夏时制有关吗?其他?谢谢.

Whats wrong? Does it have something to do with daylight saving time? Other? Thanks.

推荐答案

似乎是时区问题...我以为NSLog将默认为当地时区-但似乎默认为GMT ...

Seems like this is a Time Zone issue... I thought NSLog would default to the local time zone - but it seems to default to 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实际上似乎可以满足我的要求...

... so my original cleanDate actually seems to do what I want after all...

这篇关于比较日期-忽略小时部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆