How to get Current, Previous, Tomorrow's Date, and Time in Swift with examples
This tutorial explains getting the date and time in local, UTC, and timezone in swift
- Current Date
- Tomorrow’s Date
- Yesterday Date
How to get Today, yesterday and Tomorrow Local Date and time in swift
First, get the Current Date. Next, pass the current date Calendar. The date function with byAdding=.day
and value is one day. -1 day is used to pass Here is an example
import Foundation;
let todayDate = Date()
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: todayDate)!
var yesterday = Calendar.current.date(byAdding: .day, value: -1, to: todayDate)!
// Current Date
print(todayDate)
// Tomorrow's Date
print(tomorrow)
// Yesterday's Date
print(yesterday)
Output:
2022-10-30 13:56:10 +0000
2022-09-08 13:56:10 +0000
2022-09-06 13:56:10 +0000
You can also write an extension to the Date of class
Date
class added two extension methods.
- the tomorrow method
- the yesterday method
import Foundation;
extension Date {
var tomorrow: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: self)!
}
var yesterday: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: self)!
}
}
let todayDate = Date()
// Current Date
print(todayDate)
// Tomorrow's Date
print(todayDate.tomorrow)
// Yesterday's Date
print(todayDate.yesterday)