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)
}
}
}
When i try
date = Date().onlyDate
It returns the previous date. You can check the screenshot that its giving me 14th April while it should have been 15th
Let me guess, you are in the GMT+6 time zone, aren't you?
When Date
s are printed, they always show up in UTC.
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.
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))