Why does date only object always has 16:00:00 time? instead of 00:00:00

So ive read there is no feature in the Foundation package that outputs a date only object.

Ive tried variations seen in forum posts. One of them is like this.

But i am confused why the output is always 16:00:00 +0000 for the time instead of 00:00:00 +0000?

This is the code

Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!

16:00:00 is 4PM. Instead of 12:00AM

When I run it in this site online swift playground https://online.swiftplayground.run/

i get this output 2023-02-26 23:00:00 +0000

I figure this could be because of timezone. But is there a way to get a date object where the value of time is midnight? 00:00:00?

Thoughts?

Replies

It has to do with TimeZone.

Consider the following code:

let f = DateFormatter()
f.timeZone = TimeZone(identifier: "UTC")
f.dateFormat = "yyyy/MM/dd HH:mm:ss"
let time = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
var timeString = f.string(from: time)
print("UTC", timeString)
f.timeZone = TimeZone(identifier: "Europe/Paris")
timeString = f.string(from: time)
print("Paris", timeString)

You'll get:

  • UTC 2023/02/26 23:00:00
  • Paris 2023/02/27 00:00:00

Get all time zones here: https://stackoverflow.com/questions/47494222/getting-the-city-country-list-in-ios-time-zone

  • there is no other way without having to set a timezone? i thought the default would be the users current timezone.

    i just want a date at 12 midnight. will try converting to string then date. may be overkill but if it works, im ok with it

  • I made an extension of Date instead to convert utc timezone to user's timezone. Just my assumption, they probably did it this way since ios is meant for front end use, so Date() with UTC is the best option to start with. Then users can just convert it to their local timezone.

Add a Comment