gpt4 book ai didi

ios - NSDate 通过 NSCalendar 的 dateFromComponent

转载 作者:行者123 更新时间:2023-11-29 13:37:35 25 4
gpt4 key购买 nike

我对这段代码有疑问:

+ (NSDate *)dateByMovingToBeginningOfDay:(NSDate *)date
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:date];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];

return [[NSCalendar currentCalendar] dateFromComponents:parts];
}

+ (NSDate *)dateByMovingToEndOfDay:(NSDate *)date
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *parts = [[NSCalendar currentCalendar] components:flags fromDate:date];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];

return [[NSCalendar currentCalendar] dateFromComponents:parts];
}

+ (BOOL)checkForReportInDate:(NSDate *)date forUser:(User *)user
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = appDelegate.managedObjectContext;

NSDate *startDate = [NSDate dateByMovingToBeginningOfDay:date];
NSDate *endDate = [NSDate dateByMovingToEndOfDay:date];

NSLog(@"apply date: %@", date.description);
NSLog(@"start date: %@", startDate.description);
NSLog(@"end date: %@", endDate.description);

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"Report" inManagedObjectContext:context];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"user == %@ AND (date > %@ AND date < %@)", user, startDate, endDate];
fetchRequest.fetchLimit = 1;

NSError *error = nil;

NSUInteger reportExist = [context countForFetchRequest:fetchRequest error:&error];

if(error != nil) {
NSLog(@"Error: %@", [error localizedDescription]);
return NO;
}

if(reportExist > 0) {
return 1;
}
else {
return 0;
}
}

它生成了错误的开始日期...在我的控制台中有

2012-04-12 14:34:46.456 iFood Pro[23820:fb03] 将报告保存到数据库2012-04-12 14:34:46.458 iFood Pro[23820:fb03] 申请日期:2012-04-12 12:34:41 +00002012-04-12 14:34:46.458 iFood Pro[23820:fb03] 开始日期:2012-04-11 22:00:00 +00002012-04-12 14:34:46.459 iFood Pro[23820:fb03] 结束日期:2012-04-12 21:59:59 +0000

开始日期应为 2012-04-12 00:00:00 +0000 而不是 2012-04-11 22:00:00 +0000为什么会有这种行为?我快疯了!

最佳答案

已修复,问题是时区...使用 [parts setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 解决了问题

关于ios - NSDate 通过 NSCalendar 的 dateFromComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10123746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com