How to separate the date and time components of NSDate() in Swift?

一曲冷凌霜 提交于 2019-12-10 23:32:08

问题


Would anyone be able to tell me how to separate the date and time components of NSDate() in Swift? I saw a few things about separating the date itself into components (day, month, year), but nothing really about how to get the time only or the day, month, and year only.

Basically, I'm trying to filter data on a table by date, but to also display the time the entry was made. I tried using the plain ol' NSDate(), but then the filtering didn't work because filtering by just today's date didn't yield results because the times those entries were made will always be less than the current time.


回答1:


You need to use NSCalendar to break a date apart, using NSCalendarUnit to specify what components you want.

let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Month, .Day, .Year, .Hour, .Minute], fromDate: NSDate())
print("Hour: \(components.hour)")
print("Minute: \(components.minute)")
print("Day: \(components.day)")
print("Month: \(components.month)")
print("Year: \(components.year)")


来源:https://stackoverflow.com/questions/38400325/how-to-separate-the-date-and-time-components-of-nsdate-in-swift

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