如何在Swift中分隔NSDate()的日期和时间组件? [英] How to separate the date and time components of NSDate() in Swift?

查看:99
本文介绍了如何在Swift中分隔NSDate()的日期和时间组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何在Swift中分隔NSDate()的日期和时间部分?我看到了一些有关将日期本身分为几部分(天,月,年)的事情,但是关于如何仅获取时间或仅获取日,月和年的内容并没有真正的意义。

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.

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

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.

推荐答案

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

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

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

这篇关于如何在Swift中分隔NSDate()的日期和时间组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆