Introduction to Working with Dates and Time in Swift
Working with dates and time is one of the key tasks when developing applications for iOS and macOS. From simply displaying the current date to complex calculations of time intervals and managing time zones, Swift provides a powerful and flexible toolkit. In this article, we will cover the main classes and structures: Date, DateFormatter, Calendar, DateComponents, and TimeInterval. You will learn how to create, format, compare, and manipulate dates in practice.
Main Classes and Structures
Swift uses several fundamental types for working with dates. Let's look at each of them.
- Date — a structure representing a specific moment in time. It is independent of calendar or time zone.
- DateFormatter — a class for converting a date to a string and back.
- Calendar — a structure describing a calendar (Gregorian, Buddhist, etc.) and providing methods for working with date components.
- DateComponents — a structure for storing individual date components (year, month, day, hour, minute, etc.).
- TimeInterval — a type (Double) representing a number of seconds.
Working with Date and DateFormatter
Let's start with the simplest: getting the current date and displaying it to the user.
Getting the Current Date
import Foundation
let currentDate = Date()print("Current date and time: \\(currentDate)")// Output: Current date and time: 2025-04-05 12:30:00 +0000Formatting a Date
To make the date look familiar, use DateFormatter:
let formatter = DateFormatter()formatter.dateFormat = "dd.MM.yyyy HH:mm"let dateString = formatter.string(from: currentDate)print("Formatted date: \\(dateString)")// Output: Formatted date: 05.04.2025 12:30Parsing a String into a Date
let dateString = "2025-04-05 14:00"formatter.dateFormat = "yyyy-MM-dd HH:mm"if let parsedDate = formatter.date(from: dateString) { print("Parsed date: \\(parsedDate)")} else { print("Parsing error")}Important: always check that date(from:) does not return nil, otherwise the application may crash.
Date Manipulations with Calendar and DateComponents
Often you need to add days, months, or calculate the difference between dates. This is where Calendar comes to the rescue.
Adding and Subtracting Time
let calendar = Calendar.currentlet oneWeekLater = calendar.date(byAdding: .day, value: 7, to: currentDate)!let oneMonthAgo = calendar.date(byAdding: .month, value: -1, to: currentDate)!
print("In a week: \\(formatter.string(from: oneWeekLater))")print("A month ago: \\(formatter.string(from: oneMonthAgo))")Extracting Date Components
let components = calendar.dateComponents([.year, .month, .day, .hour], from: currentDate)if let year = components.year, let month = components.month { print("Today: \\(year)-\\(month)")}Creating a Date from Components
var newComponents = DateComponents()newComponents.year = 2025newComponents.month = 12newComponents.day = 25newComponents.hour = 10newComponents.minute = 0
if let christmas = calendar.date(from: newComponents) { print("Christmas: \\(formatter.string(from: christmas))")}Comparing Dates and Working with TimeInterval
Swift allows you to easily compare dates and calculate time intervals.
Comparing Dates
let now = Date()let futureDate = calendar.date(byAdding: .day, value: 10, to: now)!
if futureDate > now { print("