Swift Add day, week, month, and year to the current date in the example

This tutorial shows how to do the following things in Swift

  • Get Yesterday’s date
  • Get Tomorrow’s date
  • Add and subtract 1 week to the Current date
  • Add and subtract 1 month to the Current date
  • Add and subtract 1 year to the Current date

To add any value to the Current Date, Calendar provides the date method with the below syntax

date(byAdding:to:options:)

byAdding: adding .day or .month,.year and .weekOfYear value: value can be positive or negative to: specify current date.

How to add and subtract a day, month, week, and year from a current date

Current date returns using new Date() object.

  • Example to get the Current Date

Date() object returns the current date and time

import Foundation
let date = Date()
print(date)

Output:

2022-10-30 11:16:16 +0000
  • example to get Yesterday’s Date

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
  • example to get Tomorrow’s Date

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
  • example to add and subtract 1 week to the current Date

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
  • example to add and subtract 1 month to the current Date

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
  • example to add and subtract 1 year to the current Date

The date function added with byAdding: .year and value 1 to get next year today date. The 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