I'm trying create a Date
object with day, month and year, but the function of Calendar is returning nil
.
let calendar = Calendar.current
let date = calendar.dateComponents([.day,.month,.year], from: Date()).date! // <- nil
How I create a Date
object only with day, month and year?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With