Ios NSDate归零小时分钟和秒

Ios NSDate归零小时分钟和秒,ios,objective-c,cocoa-touch,nsdate,Ios,Objective C,Cocoa Touch,Nsdate,我有一个NSDate,我想把小时、分钟和秒归零。我想要的结果是:2014-02-19 00:00:00+0000。我尝试了以下方法: NSUInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents* components = [[NSCalendar currentCalendar] components:flags fromDate:self.birthDateP

我有一个NSDate,我想把小时、分钟和秒归零。我想要的结果是:
2014-02-19 00:00:00+0000
。我尝试了以下方法:

NSUInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* components = [[NSCalendar currentCalendar] components:flags fromDate:self.birthDatePicker.date];
NSDate* birthDate = [[NSCalendar currentCalendar] dateFromComponents:components];

出于某种原因,我得到了这个:
2014-02-19 23:00:00+0000
。时间并没有归零。我还尝试设置
[components setHour:0]
。但我在几个小时内得到了同样的结果。你知道我做错了什么吗

看看这个库:

我也有类似的问题,我决定用它。它有很多与日期相关的功能。您需要的是:

- (NSDate *)mt_startOfCurrentDay;
关于时区。NSDate具有独立于时区的格式。您可以在NSDateFormatter实例中指定所需的时区

更新完整代码示例

NSDate *date = [NSDate date];
NSLog(@"%@", date); // 2014-02-20 11:11:40 +0000
[NSDate mt_setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSLog(@"%@", [[date mt_startOfCurrentDay] mt_stringFromDateWithISODateTime]); // 2014-02-20 00:00:00 +0000
对于其他日期格式,请使用时区和自定义日期格式设置NSDateFormatter

还有一个解决方案这一个没有库:

NSDate *date = [NSDate date];
NSLog(@"%@", date); // 2014-02-20 11:36:20 +0000
NSUInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:currentCalendar.calendarIdentifier];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents* components = [calendar components:flags fromDate:date];
date = [calendar dateFromComponents:components];
NSLog(@"%@", date); // 2014-02-20 00:00:00 +0000
顺便说一句,我有GMT+3时区总是有用的:

WWDC视频

2011<代码>第117课时-执行日历计算

2013年
第227课时-常见日期和时间挑战的解决方案


其中包含您可能需要的信息:


会话227@13m25s,“常见操作”/“计算午夜”。请在NSDate考虑此类别:

@interface NSDate (Utilities)
- (NSDate *) dateAtStartOfDay;
@end

@implementation
- (NSDate *) dateAtStartOfDay
{

   NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:self];
   [components setHour:0];
   [components setMinute:0];
   [components setSecond:0];
   return [[NSCalendar currentCalendar] dateFromComponents:components];
}
@end

代码取自Erika Sadun

考虑时区。。。您的本地时区是GMT+1,当您使用NSLog记录日期时,它以GMT形式给出其时间。时区的需要取决于用例。如果你硬编码你的时区到日期,你将很容易打破它的用户在不同的时区。你需要的是一个带有样式或格式的简单日期格式化程序。哎哟……我误解了你想要的,现在我为你发布了一个正确的函数you@Andres,我已经更新了我的帖子,我希望,现在都是问题的警告?这和OP的方式是一样的。他的比较干净,不一样。。。OP方式不考虑小时、分钟、秒等。。。不使用这些单位标志与将它们设置为零完全相同。运行他的代码和你的代码,让你自己看看。你完全正确,他们有相同的时间。OP和mine的代码显示为23,这是localeTimeZone偏移量为3600的原因。记录NSDate以绝对参考的形式为您提供时间。要在我的国家有一个开始日期时间,需要减去(或加上)偏移量。