THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial shows how to do the following things in Swift
To add any value to the Current Date, Calendar
provides the date
method with the below syntax
date(byAdding:to:options:)
byAdding
: tells to add .day
or .month
,.year
and .weekOfYear
value
: value can be positive or negative
to
: specify current date.
Current date returns using new Date()
object.
Date() object returns the current date and time
import Foundation
let date = Date()
print(date)
Output:
2022-10-30 11:16:16 +0000
Date() object returns the current date and time
import Foundation
let date = Date()
// yesterday date
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)!
print(yesterday)
Output:
2022-10-30 11:16:16 +0000
import Foundation
let date = Date()
// tomorrows date
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: date)!
print(tomorrow)
Output:
2022-10-30 11:16:16 +0000
import Foundation
let date = Date()
// add 1 week to current date
let nextWeek = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: date)!
print(nextWeek)
// substract 1 week to current date
let previousWeek = Calendar.current.date(byAdding: .weekOfYear, value: 1, to: date)!
print(previousWeek)
Output:
2022-10-30 11:29:12 +0000
2022-10-30 11:29:12 +0000
import Foundation
let date = Date()
// add 1 month to current date
let onemonth = Calendar.current.date(byAdding: .month, value: 1, to: date)!
print(onemonth)
// substract 1 month to current date
let previousMonth = Calendar.current.date(byAdding: .month, value: -1, to: date)!
print(previousMonth)
Output:
2022-08-03 11:29:12 +0000
2022-10-30 11:29:12 +0000
date function added with byAdding: .year and value 1 to get next year today date. date function added with byAdding: .year and value -1 to get previous year today date
// add 1 year to current date
let nextYear = Calendar.current.date(byAdding: .year, value: 1, to: date)!
print(nextYear)
// substract 1 year to current date
let previousYear = Calendar.current.date(byAdding: .year, value: -1, to: date)!
print(previousYear)
Output:
2023-07-03 11:31:01 +0000
2021-07-03 11:31:01 +0000
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts