Augusto
Augusto

Reputation: 4243

Date from Calendar.dateComponents returning nil in Swift

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?

Upvotes: 8

Views: 8989

Answers (2)

Martin R
Martin R

Reputation: 539815

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.

Upvotes: 19

rmaddy
rmaddy

Reputation: 318824

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.

Upvotes: 8

Related Questions