'How do you get last weeks date in swift in YYYY-MM-DD format?

How can I display date of one week ago in the format of YYYY-MM-DD like this one "2015-02-18" in Swift



Solution 1:[1]

You can use Calendar's date(byAdding component:) to calculate today minus a week and then you can format your date as desired using DateFormatter:

let lastWeekDate = Calendar(identifier: .iso8601).date(byAdding: .weekOfYear, value: -1, to: Date())!
let dateFormatter = DateFormatter()
dateFormatter.calendar = .init(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let lastWeekDateString = dateFormatter.string(from: lastWeekDate)

Solution 2:[2]

To get the date in a specific format you can use the NSDateFormatter:

var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var todayString:String = dateFormatter.stringFromDate(todaysDate)

NSDate() returns the current date

For calculating date you should use calendar

let calendar = NSCalendar.currentCalendar()
let weekAgoDate = calendar.dateByAddingUnitdateByAddingUnit(.WeekOfYearCalendarUnit, value: -1, toDate: NSDate(), options: nil)!
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var aWeekAgoString:String = dateFormatter.stringFromDate(weekAgoDate)

Solution 3:[3]

Swift 3:

        let lastWeekDate = NSCalendar.current.date(byAdding: .weekOfYear, value: -1, to: NSDate() as Date)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        var aWeekBefore:String = dateFormatter.string(from: lastWeekDate!)

Solution 4:[4]

Would extending NSDate be a bad idea?

import UIKit

extension NSDate {

    func previousWeek() -> NSDate {
        return dateByAddingTimeInterval(-7*24*60*60)
    }

    func asString(format:String) -> String {
        var dateFormatter : NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.stringFromDate(self)
    }
}

NSDate().previousWeek().asString("yyyy-MM-dd")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Gokila Dorai
Solution 4 seventy2eleven