3

After import Foundation, I wrote a class called ‘Employee’. One of its properties is of type Date. My questions is: when instantiating Employee, how do I format its Date property value? (I've tried YYYY-MM-DD, MM-DD-YYYY, and a few others, but Xcode won’t accept.)

Here's the class:

class Employee {
let name: String
let address: String
let startDate: Date
let type: EmployeeType  

init(name: String, address: String, startDate: Date, type: EmployeeType) {
    self.name = name
    self.address = address
    self.startDate = startDate
    self.type = type
}

And here's an attempt to create an instance (2017-10-19 isn't accepted):

let nick = Employee(name: "Nick", address: "61", startDate: 2017-10-19, type: EmployeeType.traditional)

Many thanks,
Nick

williej926
  • 123
  • 10
Nick
  • 31
  • 3

1 Answers1

1

If you are looking for a date/time literal syntax, Swift doesn't have one! The shortest method I've found is by constructing a DateComponents:

let date = DateComponents(calendar: .current, year: 2017, month: 10, day: 19).date!

Another thing that I see all too common here on StackOverflow: beware the timezone. If you print(date) and don't get back the date/time you asked for, think about converting your requested time in GMT as that what's Date always uses

Code Different
  • 90,614
  • 16
  • 144
  • 163