【问题标题】:How to separate the date and time components of NSDate() in Swift?如何在 Swift 中分离 NSDate() 的日期和时间组件?
【发布时间】:2016-11-18 21:54:25
【问题描述】:

谁能告诉我如何在 Swift 中分离 NSDate() 的日期和时间组件?我看到了一些关于将日期本身分成组件(日、月、年)的事情,但没有真正了解如何仅获取时间或仅获取日、月和年。

基本上,我试图按日期过滤表中的数据,但也显示输入的时间。我尝试使用普通的 ol' NSDate(),但是过滤不起作用,因为仅按今天的日期进行过滤不会产生结果,因为这些条目的生成时间总是小于当前时间。

【问题讨论】:

  • 查看NSDateComponents

标签: swift date time filtering nsdate


【解决方案1】:

您需要使用 Calendar 将日期分开,使用 CalendarUnit 指定您想要的组件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多