Swift: What day is today?
Video: Swift: What day is today? by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: What Day Is Today?
In this tutorial, you'll learn how to use Swift's Date and DateFormatter classes to find out the current day of the week. This is a practical example for beginners to understand how to work with dates and format them into readable strings.
Code
import Foundation
// Get the current date and time
let today = Date()
// Create a DateFormatter to format the date into a day name
let formatter = DateFormatter()
formatter.dateFormat = "EEEE" // "EEEE" gives the full name of the day (e.g., Monday)
// Convert the current date into the day of the week string
let dayOfWeek = formatter.string(from: today)
// Print the result
print("Today is \(dayOfWeek).")
Key Points
- Use the Date() class to get the current date and time in Swift.
- DateFormatter allows you to format dates into readable strings using format patterns.
- The format string "EEEE" returns the full name of the day of the week.
- Combining Date and DateFormatter makes it easy to display human-friendly date information.