Reputation: 927
How do you convert a DateComponents to a Date Object. Currently, I have following code
Calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
but I'm getting an error stating "No 'date' candidates produce the expected contextual result type 'Date'
Sorry for the basic question, but I'm still struggling with how to work with dates in Swift
Upvotes: 4
Views: 6501
Reputation: 81
//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()
Upvotes: 0
Reputation: 285072
You cannot call date(from
on the type. You have to use an instance of the calendar, either the current
calendar
Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
or a fixed one
let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
Upvotes: 15