【问题标题】:How do i know if a specific date is a month, or a week to an parent date?我怎么知道一个特定的日期是一个月还是一周的父母日期?
【发布时间】:2020-02-28 16:15:59
【问题描述】:

假设我有一个程序可以提醒用户他们的约会,从当前日期到约会日期,我想知道某个特定日期是约会的一周还是约会的一个月。

var startDate = startDate
let calendar = Calendar.current

let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"

while startDate <= endDate {

    var  newDate = calendar.date(byAdding: .day, value: 1, to: startDate)!


    if newDate is a month to endDate {

        //schedule reminder
    }

    if newDate is a week to endDate{

        //schedule reminder
    }

我如何检查当前日期是否是约会的一周/一个月?

【问题讨论】:

    标签: ios swift calendar nsdate


    【解决方案1】:

    您不需要使用任何日期比较,您可以简单地使用Calendar.date(byAdding:value:to:) 生成通知日期并传递正确的组件。要将日期设置在 endDate 之前 1 周/月,请将 -1 传递给 value。

    let oneWeekBeforeAppointment = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: endDate)!
    let oneMonthBeforeAppointment = Calendar.current.date(byAdding: .month, value: -1, to: endDate)!
    

    【讨论】:

    • 为什么我需要通过-1 如果我通过1 你知道其中的含义吗?
    • @BigFire 负值意味着将日期移至过去,而正值意味着将日期移至未来。因此,如果您将-1 更改为1,则意味着日期将是前一个日期之后,而不是之前 1 周/月。
    【解决方案2】:

    试试这个以天计算持续时间

    func DateFormat() -> DateFormatter {
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "dd/MM/yyyy"
      dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
      return dateFormatter
    }
    
    var appointementDate: Date?
    var today = Date()
    
    appointementDate = DateFormat().date(from: "22/02/2020")
    today = DateFormat().date(from: DateFormat().string(from: today))!
    
    let timeInterval = Int(exactly: (today.timeIntervalSince(appointementDate!))) ?? 0
    print("\(timeInterval/86400) days left")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多