Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 499
John Pollard Avatar asked Feb 18 '15 15:02

John Pollard


People also ask

What is en_US_POSIX?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.


4 Answers

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)
like image 101
Leo Dabus Avatar answered Oct 20 '22 01:10

Leo Dabus


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)
like image 29
Jérôme Avatar answered Oct 19 '22 23:10

Jérôme


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!)
like image 23
Gokila Dorai Avatar answered Oct 20 '22 01:10

Gokila Dorai


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")
like image 45
seventy2eleven Avatar answered Oct 20 '22 00:10

seventy2eleven