如何以 YYYY-MM-DD 格式获取 swift 中的上周日期?

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

如何以 YYYY-MM-DD 的格式显示一周前的日期,例如 Swift

中的“2015-02-18”

要获取特定格式的日期,您可以使用 NSDateFormatter:

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

NSDate() returns 当前日期

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)

您可以使用日历的 date(byAdding component:) 来计算今天减去一周,然后您可以使用 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)

扩展 NSDate 是个坏主意吗?

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")

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!)