Ad space (banner)
๐ŸฆSwift Lessons
Lesson 36 / 68

Building and Displaying Dates (Basic Year/Month/Day Operations)

In this lesson you will learn the basics of working with dates through Swift's DateComponents and Calendar, so you can build a date and find its day of the week. This is for anyone searching for "Swift DateComponents Calendar how to use".

DateComponents together with Calendar lets you assemble and work with a specific date. Reading the day of the week is straightforward too.

The sample code sets the year, month, and day on DateComponents, builds the date with Calendar(identifier: .gregorian), and gets the weekday index with calendar.component(.weekday, from: date). Notice how that index is then looked up in an array of names.

A common stumbling block for beginners is how the weekday index is counted. Note the - 1 when computing weekdayIndex - you have to get used to how the Calendar class numbers the days.

In real-world development, DateFormatter gives you far more flexible display formats, and date handling is unavoidable background knowledge for any date-driven app, from booking systems to event calendars.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)