How to get NSDate for 00:00 on the day of [NSDate date]?

前端 未结 3 1879
攒了一身酷
攒了一身酷 2020-12-15 10:04

I need to get an NSDate object for 00:00(beginning of the day) from [NSDate date], let\'s say if currently it is 11:30am(returned by [NSDate date]), on 01/06/2012, now I nee

3条回答
  •  忘掉有多难
    2020-12-15 10:09

    Converting NSDate to NSString can be helpful but if you need to keep a NSDate object for further processing, here is your solution to have your real morningStart NSDate object set at 00:00:00 time, with care of the timezone as well... As you will see you were not so far from the solution :

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:now];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    int timeZoneOffset = [destinationTimeZone secondsFromGMTForDate:now] / 3600;
    [components setHour:timeZoneOffset];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *morningStart = [calendar dateFromComponents:components];
    

提交回复
热议问题