Date from Calendar.dateComponents returning nil in Swift
As a supplement to rmaddy's answer, the reason why your code returns nil
is that you try to convert DateComponents
to a Date
without specifying a
Calendar
.
If that conversion is done with a calendar method
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: Date())
let date = calendar.date(from: components)
or if you add the calendar to the date components
let calendar = Calendar.current
let date = calendar.dateComponents([.day, .month, .year, .calendar], from: Date()).date
then you'll get the expected result.
If you want to strip off the time portion of a date (set it to midnight), then you can use Calendar startOfDay
:
let date = Calendar.current.startOfDay(for: Date())
This will give you midnight local time for the current date.
If you want midnight of the current date for a different timezone, create a new Calendar
instance and set its timeZone
as needed.