How can I display date of one week ago in the format of YYYY-MM-DD like this one "2015-02-18" in Swift
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.
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)
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)
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!)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With