Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}

When i try

date = Date().onlyDate 

My Output

It returns the previous date. You can check the screenshot that its giving me 14th April while it should have been 15th

like image 457
Ahsan Aasim Avatar asked Mar 31 '26 20:03

Ahsan Aasim


1 Answers

Let me guess, you are in the GMT+6 time zone, aren't you?

When Dates 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))
like image 134
Sweeper Avatar answered Apr 03 '26 08:04

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!