Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateComponents giving wrong date

I am trying to convert today's date using DateComponents:

let calendar = Calendar.current        
//add today's date
var todayDate = Date()
var dateComponents = calendar.dateComponents([.day, .month, .year], from: todayDate)
dateComponents.timeZone = TimeZone.current
todayDate = calendar.date(from: dateComponents)!

While debugging I found that after declaring todayDate, its value was 2016-11-11 07:44:44 +0000. After using dateComponents, the value changed to 2016-11-10 18:30:00 +0000. Whereas according to my location, the day should be 11th November, and the time should be somewhere between 1 or 2 PM. Why is this happening?

like image 769
StudentX Avatar asked May 13 '26 17:05

StudentX


1 Answers

You haven't specified a timezone, nor hours minutes and seconds in your components. So, all these values are assumed to be zero. The resulting time is at midnight GMT on the year, month and day that you specified.

When you printed the result, you specified your current timezone, which appears to be 5h 30m different.

I'm guessing you are in India.

like image 59
Vince O'Sullivan Avatar answered May 15 '26 06:05

Vince O'Sullivan



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!