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

假如想象 提交于 2019-12-04 06:39:48

问题


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

NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
    return  [NSDate dateWithTimeIntervalSinceReferenceDate:time];

where date is the datepicker's date. So how to realise this in swift?


回答1:


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).



来源:https://stackoverflow.com/questions/34087806/how-to-change-date-picker-date-to-a-nsdate-type-but-with-zero-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!