没有时间的ios Swift日期 [英] ios Swift Date without Time
问题描述
我试图只获取意味着小时、分钟、秒为零的日期.这就是我正在尝试的
I am trying to get only date that means hours, mins, seconds are zeroes. This is what i am trying
extension Date {
var onlyDate: Date? {
get {
let calender = Calendar.current
var dateComponents = calender.dateComponents([.year, .month, .day], from: self)
dateComponents.timeZone = NSTimeZone.system
return calender.date(from: dateComponents)
}
}
}
当我尝试
date = Date().onlyDate
它返回上一个日期.您可以查看它给我的屏幕截图,它是 4 月 14 日,而它应该是 15 日
It returns the previous date. You can check the screenshot that its giving me 14th April while it should have been 15th
推荐答案
让我猜猜,你在 GMT+6 时区,不是吗?
Let me guess, you are in the GMT+6 time zone, aren't you?
打印Date
时,它们总是以UTC显示.
When Date
s are printed, they always show up in UTC.
2019-04-14 18:00 UTC 与 2019-04-15 00:00 在您当地的时区相同.
2019-04-14 18:00 UTC is the same as 2019-04-15 00:00 in your local time zone.
你的代码没有错.它工作正常.
Your code is not wrong. It works fine.
要在您的时区查看它,请使用 DateFormatter
并设置 timeZone
属性:
To see it in your time zone, use a DateFormatter
and set the timeZone
property:
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .full
formatter.timeZone = TimeZone.current
print(formatter.string(from: Date().onlyDate))
这篇关于没有时间的ios Swift日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!