简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM