Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Getting Date from Month, Day, Year Components

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

like image 842
user3628240 Avatar asked Oct 16 '25 20:10

user3628240


1 Answers

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))
like image 101
vadian Avatar answered Oct 18 '25 13:10

vadian