Add Days, Months or Years to Current Date in Swift

In this short blog post, I am going to share with you a few code examples on how to work with dates in Swift.  I will use DateComponents to add more days, months, or years to the current Date object in Swift.

Adding Date

let monthsToAdd = 2
 let daysToAdd = 1
 let yearsToAdd = 1
 let currentDate = Date()
 
 var dateComponent = DateComponents()
 
 dateComponent.month = monthsToAdd
 dateComponent.day = daysToAdd
 dateComponent.year = yearsToAdd
 
 let futureDate = Calendar.current.date(byAdding: dateComponent, to: currentDate)
 
 print(currentDate)
 print(futureDate!)

Or you can do it this way:

let monthsToAdd = 2

var newDate = Calendar.current.date(byAdding: .month, value: monthsToAdd, to: Date())
newdate = Calendar.current.date(byAdding: .day, value: daysToAdd, to: newDate!)
print(newDate)

Adding Date and Time

Or we can use DateComponents and set hours, minutes, and seconds as well:

import UIKit
class ViewController: UIViewController {
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
 
        let monthsToAdd = 2
        let daysToAdd = 1
        let yearsToAdd = 1
        let currentDate = getCurrentDate()
 
        var dateComponent = DateComponents()
        
        dateComponent.month = monthsToAdd
        dateComponent.day = daysToAdd
        dateComponent.year = yearsToAdd
        
        let futureDate = Calendar.current.date(byAdding: dateComponent, to: currentDate)
        
        print(currentDate)
        print(futureDate!)
  
    }
    
    func getCurrentDate()-> Date {
        var now = Date()
        var nowComponents = DateComponents()
        let calendar = Calendar.current
        nowComponents.year = Calendar.current.component(.year, from: now)
        nowComponents.month = Calendar.current.component(.month, from: now)
        nowComponents.day = Calendar.current.component(.day, from: now)
        nowComponents.hour = Calendar.current.component(.hour, from: now)
        nowComponents.minute = Calendar.current.component(.minute, from: now)
        nowComponents.second = Calendar.current.component(.second, from: now)
        nowComponents.timeZone = NSTimeZone.local
        now = calendar.date(from: nowComponents)!
        return now as Date
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!