Swift-从月,日,年组件中获取日期

use*_*240 0 date ios swift swift4

如何将DateComponents转换为Date对象。目前,我有以下代码

Calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误说明 "No 'date' candidates produce the expected contextual result type 'Date'

抱歉,这个基本问题很严重,但是我仍然在如何在Swift中处理日期方面仍在努力

vad*_*ian 5

您无法调用date(from该类型。您必须使用日历的一个实例,即current日历

Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
Run Code Online (Sandbox Code Playgroud)

或固定的

let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
Run Code Online (Sandbox Code Playgroud)