Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
Augusto Avatar asked Sep 14 '18 19:09

Augusto


2 Answers

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.

like image 172
Martin R Avatar answered Sep 25 '22 22:09

Martin R


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.

like image 31
rmaddy Avatar answered Sep 22 '22 22:09

rmaddy