Swift: What is the exact day of 2023-01-02
Video: Swift: What is the exact day of 2023-01-02 by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: What is the Exact Day of 2023-01-02
In Swift, you can easily find the exact day of the week for any given date using the Calendar and DateFormatter classes. This example demonstrates how to determine the weekday name for January 2, 2023, by parsing the date string and formatting the output accordingly.
Code
import Foundation
// Define the date string
let dateString = "2023-01-02"
// Create a DateFormatter to parse the string into a Date object
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// Convert the string to a Date
if let date = dateFormatter.date(from: dateString) {
// Create another DateFormatter to get the weekday name
let weekdayFormatter = DateFormatter()
weekdayFormatter.dateFormat = "EEEE" // Full weekday name, e.g. Monday
// Get the weekday string
let weekday = weekdayFormatter.string(from: date)
print("The day of \(dateString) is \(weekday).")
} else {
print("Invalid date format.")
}
Key Points
- Use DateFormatter to convert a date string into a Date object in Swift.
- Set the dateFormat property to match the input string format exactly.
- Use a second DateFormatter with "EEEE" format to get the full weekday name.
- Always safely unwrap the optional Date returned by date(from:) to avoid runtime errors.