12

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

Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45
John Pollard
  • 3,729
  • 3
  • 24
  • 50
  • Im not sure why my question is getting voted down. Did I do something wrong in my question? – John Pollard Feb 18 '15 at 15:56
  • You mean your question. That's because you did not post any code showing what you tried and what's not working. – Leo Dabus Feb 18 '15 at 15:58
  • oh okay, thanks! I knew NSDate gave the current date but I didnt know adding a date unit would give me a past date. So I guess Ill just post code thats obviously wrong next time? – John Pollard Feb 18 '15 at 16:00
  • Look at `NSCalendar`, specifically look on SO for similar questions regarding `NSCalendar`. There're undoubtedly numerous examples here, or even google for it. – David Berry Feb 18 '15 at 22:02

4 Answers4

43

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)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • I meant to comment and vote yours up. You submitted first with a working solution. I didn't want to rob you of points. – John Pollard Feb 18 '15 at 15:52
  • 1
    With Swift 2 you should now use ".WeekOfYear" – Philipp Otto Nov 16 '15 at 14:14
  • @leo Dabus will appreciate if you answer my question https://stackoverflow.com/questions/45238994/get-previous-current-and-next-weeks-excluding-saturday-and-sunday – Maddy Jul 21 '17 at 13:31
5

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)
Community
  • 1
  • 1
Jérôme
  • 8,016
  • 4
  • 29
  • 35
  • 1
    Note that to get the interval use: `var interval: NSTimeInterval = -60 * 60 * 24 * 7; var aWeekAgoToday = NSDate(timeInterval: interval, sinceDate: todaysDate)` – kellanburket Feb 18 '15 at 15:46
  • If you want more details: http://stackoverflow.com/questions/26942123/nsdate-of-yesterday – Jérôme Feb 18 '15 at 15:48
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!)
Gokila Dorai
  • 100
  • 5
1

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")
  • 1
    The extension is ok but the way you implement it is not. first you don't need a function because there is no parameters, try creating a read-only computed property. You should also use the dateByAddingUnit instead of adding time interval. – Leo Dabus Feb 18 '15 at 16:58