How to change date picker date to a NSDate type bu

2019-03-06 08:33发布

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条回答
聊天终结者
2楼-- · 2019-03-06 09:11

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

查看更多
登录 后发表回答