How to change date picker date to a NSDate type but with zero seconds

后端 未结 1 697
清酒与你
清酒与你 2021-01-28 15:12

I have a date picker that returns me a NSdate value. And I want to have a date value of seconds set to 0. I have the code to do it in objective c as

NSTimeInterv         


        
相关标签:
1条回答
  • 2021-01-28 15:55

    It is almost identical in Swift:

    let date = NSDate()
    let ti = floor(date.timeIntervalSinceReferenceDate/60.0) * 60.0
    let date1 = NSDate(timeIntervalSinceReferenceDate: ti)
    

    The same can be achieved with NSCalendar methods:

    let cal = NSCalendar.currentCalendar()
    var date2 : NSDate?
    cal.rangeOfUnit(.Minute, startDate: &date2, interval: nil, forDate: date)
    

    and this has the great advantage that it can easily be adapted for larger time units like days, months, etc. which do not have a fixed length (e.g. a day can have 23, 24, or 25 hours in regions with daylight saving time).

    0 讨论(0)
提交回复
热议问题