如何以YYYY-MM-DD的格式显示一周前的日期,例如Swift中的这个“2015-02-18”
答案 0 :(得分:26)
您可以使用日历date(byAdding component:)
计算今天减一周,然后您可以使用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)
答案 1 :(得分:4)
要以特定格式获取日期,您可以使用NSDateFormatter
:
var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var todayString:String = dateFormatter.stringFromDate(todaysDate)
NSDate()
返回当前日期
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)
答案 2 :(得分:1)
扩展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")
答案 3 :(得分:1)
斯威夫特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!)