In Swift, Date and Time manipulation is quite different from traditional C-based programming languages like Objective-C and C++. In this tutorial, you will learn how to work with Date and Time using built-in classes and functions in Swift.
You can get the current date and time using the Date class provided in Swift. Here's an example:
let currentDate = Date()
print("Current Date: \(currentDate)")}
You can format dates using DateFormatter class. Here's an example:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let strDate = dateFormatter.string(from: currentDate)
print("Formatted Date: \(strDate)")}
In the above example, we created an instance of DateFormatter class and set its dateFormat property. Then we used this instance to format the current date object and print it to the console.
A time interval is the difference between two dates. You can get time intervals using the timeIntervalSince() method provided in the Date class. Here's an example:
let startDate = Date()
let endDate = Date(timeIntervalSinceNow: 1800)
let timeInterval = endDate.timeIntervalSince(startDate)
print("Time interval: \(timeInterval)")}
In the above example, we created two instances of Date class and then calculated the time interval between them using the timeIntervalSince() method. The result is printed to the console.
You can compare dates using the compare() method provided in the Date class. Here's an example:
let date1 = Date(timeIntervalSinceReferenceDate: 0)
let date2 = Date(timeIntervalSinceNow: 3600)
let result = date1.compare(date2)
if result == ComparisonResult.orderedAscending {
print("\(date1) is earlier than \(date2)")
} else if result == ComparisonResult.orderedDescending {
print("\(date1) is later than \(date2)")
} else {
print("\(date1) is equal to \(date2)")
}
In the above example, we created two instances of Date class and then compared them using the compare() method. The result is printed to the console.
You can add or subtract time intervals to/from a date using the addingTimeInterval() method provided in the Date class. Here's an example:
let date = Date()
let futureDate = date.addingTimeInterval(7200)
let pastDate = date.addingTimeInterval(-3600)
print("Future Date: \(futureDate)")
print("Past Date: \(pastDate)")}
In the above example, we created an instance of Date class and then added/subtracted time intervals to/from it using the addingTimeInterval() method. The results are printed to the console.
Summary:
In this tutorial, you learned how to work with Date and Time using built-in classes and functions in Swift. You learned how to get the current date and time, format dates, work with time intervals, compare dates, and add/subtract dates. By using these techniques, you can create sophisticated applications that deal with dates and times in a reliable and efficient manner.