我怎么知道一个特定的日期是一个月,还是一个父日期的一周?

问题描述 投票:0回答:2

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

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
2个回答
0
投票

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

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

0
投票

尝试此操作以天为单位计算持续时间

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")
© www.soinside.com 2019 - 2024. All rights reserved.