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

こ雲淡風輕ζ 提交于 2020-07-15 05:11:48

问题


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


回答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.current.date(byAdding: .weekOfYear, value: -1, to: Date())!
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let lastWeekDateString = dateFormatter.string(from: lastWeekDate)



回答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)



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



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


来源:https://stackoverflow.com/questions/28587311/how-do-you-get-last-weeks-date-in-swift-in-yyyy-mm-dd-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!