NSDate今天午夜

时间:2014-05-06 18:50:33

标签: date logic nsdate nspredicate

我正在建立一个NSPredicate来获取核心数据,其设置如下:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", todaysDate, tomorrowsDate];

我需要todaysDate今天00:00:00,我需要tomorrowsDate今天23:59:59。

我无法将todaysDate设置为[NSDate date],然后使用NSDateComponents操作小时,分钟和秒,因为[NSDate date]给了我一个比我当地早5个小时的日期实际时间(如果是5月6日晚上11点,那么[NSDate date]会给我“2014-05-07 04:00:00 +0000”,但我还是需要它认为是5月6日,而不是7日!)。

我如何操纵我在Xcode中使用的工具以使我的变量todaysDate始终在今天午夜,tomorrowsDate在明天午夜之前成为第二个?

3 个答案:

答案 0 :(得分:5)

rangeOfUnit:...的{​​{1}}方法是一种方便的方法  计算当天的开始和明天的开始 在您当地的时区

NSCalendar

这样您就可以在NSDate *now = [NSDate date]; NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *todaysDate; NSDate *tomorrowsDate; NSTimeInterval interval; [cal rangeOfUnit:NSDayCalendarUnit startDate:&todaysDate interval:&interval forDate:now]; tomorrowsDate = [todaysDate dateByAddingTimeInterval:interval]; >=的谓词中使用它:

<

获取当天的所有对象。


备注:不要让[NSPredicate predicateWithFormat:@"(date >= %@) AND (date < %@)", todaysDate, tomorrowsDate] 对象的NSLog()输出混淆你。 NSDate表示绝对时间点,对时区一无所知。 NSDate根据GMT时区打印日期,而不是在您当地的时区。

要根据您的时区打印日期,请在调试器控制台中使用NSLog(@"%@", todaysDate)(而不是p todaysDate), 或打印

po

答案 1 :(得分:1)

以下适用于我:

- (NSDate *)dateWithDate:(NSDate *)date Hour:(NSInteger)hour Minute:(NSInteger)minute Second:(NSInteger)second {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
    components.hour = hour;
    components.minute = minute;
    components.second = second;
    return [calendar dateFromComponents:components];
}

示例:

NSDate *beginningOfDay = [self dateWithDate:[NSDate date] Hour:0 Minute:0 Second:0];
NSDate *endOfDay = [self dateWithDate:[NSDate date] Hour:23 Minute:59 Second:59];

答案 2 :(得分:1)

夫特:

let cal = NSCalendar.currentCalendar()

//tip:NSCalendarUnit can be omitted, but with the presence of it, you can take advantage of Xcode's auto-completion
var comps = cal.components(NSCalendarUnit.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit, fromDate: NSDate()) 
comps.hour = 0
comps.minute = 0
comps.second = 0

let todaysDate = cal.dateFromComponents(comps)!
let tomorrowsDate = NSDate(timeInterval: 86399, sinceDate: todaysDate)

目标-C:

NSCalendar *cal = [NSCalendar currentCalendar]; 

NSDateComponents *comps = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate: [NSDate date]];    
[comps setHour:0]; 
[comps setMinute:0]; 
[comps setSecond:0];

NSDate *todaysDate = [cal dateFromComponents:comps];
NSDate *tomorrowsDate = [NSDate dateWithTimeInterval: 86399 sinceDate:todaysDate];
相关问题