是否可以从 swift 中的当前日期减去天数、月数或年数

Is it possible to subtract days, months or years from current date in swift

您好,我想从当前日期减去天数、月数或年数。 我可以使用此代码创建一个距当前日期一周后的日期。

let date = Date().addingTimeInterval(TimeInterval(86400*7))

是否可以创建一个从当前日期算起过去一周的日期?

您应该使用 Calendar 来进行这些计算,而不是硬编码 86400 一天。

if let date = Calendar.current.date(byAdding: .day, value: -7, to: Date()) {
   // Use this date
}

添加以下扩展名:

extension Date {
    func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
        return calendar.dateComponents(Set(components), from: self)
    }

    func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
        return calendar.component(component, from: self)
    }
}

使用如下扩展名:

let date = Date()

let components = date.get(.day, .month, .year)
if let day = components.day, let month = components.month, let year = components.year {
    print("day: \(day), month: \(month), year: \(year)")
}

获取与今天准确的上周日期

let lastWeekDate = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: Date())!

Swift 5

从当前日期增加或减去日、月、年的函数。

func addOrSubtractDay(day:Int)->Date{
  return Calendar.current.date(byAdding: .day, value: day, to: Date())!
}

func addOrSubtractMonth(month:Int)->Date{
  return Calendar.current.date(byAdding: .month, value: month, to: Date())!
}

func addOrSubtractYear(year:Int)->Date{
  return Calendar.current.date(byAdding: .year, value: year, to: Date())!
}

正在调用函数

//Subtracting
var daySubtractedDate = addOrSubtractDay(-7)
var monthSubtractedDate = addOrSubtractMonth(-7)
var yearSubtractedDate = addOrSubtractYear(-7)

//Adding
var dayAddedDate = addOrSubtractDay(7)
var monthAddedDate = addOrSubtractMonth(7)
var yearAddedDate = addOrSubtractYear(7)
  • 添加日期传递预期值
  • 要减去负数 值