How do I use Date, DateFormatter, and Calendar correctly?

In Swift, managing dates and times effectively is crucial for any application. The `Date`, `DateFormatter`, and `Calendar` classes work together to perform various date-related tasks such as formatting, comparing, and manipulating dates. Below is an overview of how to use these classes correctly.

Using Date, DateFormatter, and Calendar

The Date class in Swift represents a specific point in time. To display this date in a readable format, we use DateFormatter. The Calendar class provides methods for performing calculations with dates, such as adding days or determining the difference between two dates.

Example: Formatting a Date

Here’s an example of how to create a date using Date, format it using DateFormatter, and perform calculations with Calendar.

let date = Date() // Current date let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short let formattedDate = dateFormatter.string(from: date) print("Formatted Date: \(formattedDate)") // Example output: "Oct 14, 2023 at 2:15 PM" let calendar = Calendar.current if let nextWeek = calendar.date(byAdding: .weekOfYear, value: 1, to: date) { let nextWeekFormatted = dateFormatter.string(from: nextWeek) print("Next Week: \(nextWeekFormatted)") // Example output: "Oct 21, 2023 at 2:15 PM" }

Swift Date DateFormatter Calendar Date Manipulation Swift Date Example iOS Development