Date constant from year, month, day

Is there a way to create a Date constant from year, month and day? The only constructors that show up are .now and those based on some timeInterval. I'm trying to initialize some test data with known dates.

Answered by Claude31 in 824517022

Did you try this:

func makeDate(year: Int, month: Int, day: Int, hr: Int = 0, min: Int = 0, sec: Int = 0) -> Date {

    var calendar = Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone(identifier: "GMT")!
    let components = DateComponents(year: year, month: month, day: day) //, hour: hr, minute: min, second: sec)
    return calendar.date(from: components)!
}
let myDate = makeDate(year: 2025, month: 02, day: 10)
print(myDate)
Accepted Answer

Did you try this:

func makeDate(year: Int, month: Int, day: Int, hr: Int = 0, min: Int = 0, sec: Int = 0) -> Date {

    var calendar = Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone(identifier: "GMT")!
    let components = DateComponents(year: year, month: month, day: day) //, hour: hr, minute: min, second: sec)
    return calendar.date(from: components)!
}
let myDate = makeDate(year: 2025, month: 02, day: 10)
print(myDate)

Claude31,

Thanks for the reply. It works. I figured it had something to do with calendars and timezones, but I couldn't find a simple example of how to put it all together. I'll keep your function handy.

I live in the US Eastern Time Zone, so when I put in a date in GMT, it ended up the previous day, which makes sense. I changed the timezone to EST and then the date was correct.

I'm used to Python which has both naive and aware (of time zone) date time values. Apparently, Swift's Date object is aware. Does Swift have a naive date time concept?

is there a way to create a Date constant from year, month and day?

No, because the bizarrely-named Date type isn’t a date, it’s a time-point. Everywhere that I use Date in my code there’s a comment saying “actually a DateTime”.

If you want to represent a date (only), don’t use Date. I suggest writing your own type that contains either year-month-day fields or a Julian Day Number.

I'm used to Python which has both naive and aware (of time zone) date time values. Does Swift have a naive date time concept?

There is also DateComponents.

You’ll probably get frustrated by not having exactly the combination of features that you want, and unless you are constantly passing these things to and from Apple APIs, you’ll end up writing your own replacement.

Date constant from year, month, day
 
 
Q