简体   繁体   English

来自 Calendar.dateComponents 的日期在 Swift 中返回 nil

[英]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 .我正在尝试创建一个包含日、月和年的Date对象,但 Calendar 的功能返回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?如何仅使用日、月和年创建Date对象?

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 .作为补充rmaddy的答案,为什么你的代码返回nil的是,你尝试转换DateComponentsDate而没有指定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 :如果您想去除日期的时间部分(将其设置为午夜),则可以使用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.如果你想在当前日期为不同的时区的午夜,创建一个新的Calendar实例,并设置其timeZone需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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