Truncate NSDate (Zero-out time)

前端 未结 6 886
孤街浪徒
孤街浪徒 2020-12-02 19:02

I want to generate a new NSDate with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any r

6条回答
  •  遥遥无期
    2020-12-02 19:31

    unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:date];
    NSDate* dateOnly = [calendar dateFromComponents:components];
    

    date is the date you want to remove the time from.

    This separates the date and time and creates a new date with the default time (00:00:00).

    EDIT

    To take time zone into account:

    NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
    

提交回复
热议问题