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

前端 未结 3 1874
攒了一身酷
攒了一身酷 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: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.)

提交回复
热议问题