如何将DateComponents转换为Date对象。 目前,我有以下代码
Calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
但是我收到错误说明"No 'date' candidates produce the expected contextual result type 'Date'
对不起基本问题,但我仍然在努力解决如何使用Swift中的日期
答案 0 :(得分:4)
您无法在该类型上调用date(from
。您必须使用日历的实例,current
日历
Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
或固定的
let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
答案 1 :(得分:0)
//create an instance of DateComponents to keep your code flexible
var dateComponents = DateComponents()
//create the date components
dateComponents.year = 2018
dateComponents.month = 1
dateComponents.day = 15
//dateComponents.timeZone = TimeZone(abbreviation: "EST")
dateComponents.hour = 4
dateComponents.minute = 12
//make something useful out of it
func makeACalendarObject(){
//create an instance of a Calendar for point of reference ex: myCalendar, and use the dateComponents as the parameter
let targetCalendar = Calendar.current
let newCalendarObject = targetCalendar.date(from: dateComponents)
guard let newCalObject = newCalendarObject else {
return
}
print(newCalObject)
}
//call the object
makeACalendarObject()