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

前端 未结 3 1857
攒了一身酷
攒了一身酷 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];
    
    0 讨论(0)
  • 2020-12-15 10:10

    It's very easy to do this in iOS8 using startOfDayForDate:

    let date = NSDate() 
    let calendar = NSCalendar.currentCalendar(calendarIdentifier: NSGregorianCalendar)
    let dateAtStartOfDay = calendar.startOfDayForDate(date)
    

    OR you may do it in the traditional way in Swift as follows:

    let date = NSDate()
    let calendar = NSCalendar.currentCalendar(calendarIdentifier: NSGregorianCalendar)
    // Use a mask to extract the required components from today's date
    let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date)
    let dateAtStartOfDay = calendar.dateFromComponents(components)!
    print(dateAtStartOfDay) 
    

    (Note: NSDates are stored relative to GMT. So print will display the relative local time. A clear understanding of TimeZone's is essential to using NSDates properly.)

    0 讨论(0)
  • 2020-12-15 10:15

    What you doing is correct, but when you NSLog morningStart the date will be displayed in GMT time zone

    If you wanna make sure that the date is correct, convert it to NSString

     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
     NSString *strFromDate = [formatter stringFromDate:morningStart]; // this will return 2012-Jun-21 00:00:00
    
    0 讨论(0)
提交回复
热议问题