比较两个NSDate的时间,忽略日期组件 [英] Comparing the time of two NSDates, ignoring the date component
问题描述
我想比较两个NSDates与NOW([NSDate date])。
NSDate * date1 = [NSDate dateWithString: @1982-02-12 07:00:00 +0100];
NSDate * now = [NSDate dateWithString:@2012-01-25 10:19:00 +0100]; // example
NSDate * date2 = [NSDate dateWithString:@1989-02-12 15:00:00 +0100];
我想检查现在是否在date1和date2之间。在上面的例子中是这种情况。日期组件应该完全被忽略,因此只有时间组件应该进行比较。
unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * components = [calendar components:flags fromDate:date1];
NSDate * timeOnly = [calendar dateFromComponents:components];
这将给你一个日期对象,除了小时/分钟/共同价值。然后你可以使用标准的NSDate比较函数。
作为参考,这里是你的问题相反的问题:比较两个NSDates并忽略时间组件
I want to compare two NSDates with NOW ([NSDate date]).
NSDate *date1 = [NSDate dateWithString:@"1982-02-12 07:00:00 +0100"];
NSDate *now = [NSDate dateWithString:@"2012-01-25 10:19:00 +0100"]; //example
NSDate *date2 = [NSDate dateWithString:@"1989-02-12 15:00:00 +0100"];
I would like to check if now is between date1 and date2. In the example above this is the case. The date component should be completely ignored, so only the time component should be compared. How could I accomplish this?
Thanks in advance!
unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date1];
NSDate* timeOnly = [calendar dateFromComponents:components];
This will give you a date object where everything but the hours/minutes/seconds have been reset to some common value. Then you can use the standard NSDate compare functions on them.
For reference, here is the opposite question to yours: Comparing two NSDates and ignoring the time component
这篇关于比较两个NSDate的时间,忽略日期组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!