Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: startOfDay function returning 5:00 AM

Tags:

date

swift

I am calling the startOfDay function on the current date but I am getting 05:00 instead of 00:00. Any input on why this is happening would be appreciated.

Code:

let date = Calendar.current.startOfDay(for: Date())
print(date)

output:

2020-08-05 05:00:00 +0000
like image 906
Jonathan Yuan Avatar asked Dec 14 '25 14:12

Jonathan Yuan


1 Answers

That's because you're printing Date object directly it considers the time-zone. You can provide a date formatter to convert it.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = Calendar.current.startOfDay(for: Date())
let string = dateFormatter.string(from: date)
print(string)
like image 186
Frankenstein Avatar answered Dec 17 '25 00:12

Frankenstein



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!