NSDate with zero minutes and seconds

I have an NSDate in which I want zero hour, minutes and seconds. As a result, I want to: 2014-02-19 00:00:00 +0000. I tried the following:

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

For some reason, I get the following: 2014-02-19 23:00:00 +0000. The hour is not reset. I also tried to install [components setHour:0]. But I get the same result 23in a few hours. Any ideas on what I'm doing wrong?

+4
source share
3 answers

Always helpful:

WWDC Video

2011 Session 117 - Performing Calendar Calculations

2013 Session 227 - Solutions to Common Date and Time Challenges


It contains the necessary information:

Session 227 @ 13m25s , General Operations / Calculate Midnight.

0

: https://github.com/mysterioustrousers/MTDates

, . , . :

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

P.S. Btw GMT + 3

+3

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 NSDate

+2

Source: https://habr.com/ru/post/1527852/


All Articles