nsdate-Swift 3-查找两个日期之间的日历天数

我在Swift 2.3中做到的方式是:

    let currentDate         = NSDate()
    let currentCalendar     = NSCalendar.currentCalendar()

    var startDate : NSDate?
    var endDate   : NSDate?

   // The following two lines set the `startDate` and `endDate` to the start of the day

    currentCalendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: currentDate)
    currentCalendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: self)

    let intervalComps = currentCalendar.components([.Day], fromDate: startDate!, toDate: endDate!, options: [])

    print(intervalComps.day)

现在,Swift 3改变了一切。我必须使用NSCalendarNSDate,通过不断地使用as进行类型转换,或者找到Swift 3的实现方法。

在Swift 3中执行此操作的正确方法是什么?

11个解决方案
79 votes

在Swift 4中,有一个简单的方法可以获取两个日期之间的天数(或任何其他DateComponent):

let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day
flo_23 answered 2020-07-26T04:46:09Z
45 votes

事实证明,在Swift 3中这样做要简单得多。

extension Date {    

    func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {

        let currentCalendar = Calendar.current

        guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
        guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }

        return end - start
    }
}

编辑

比较两个日期的顺序应该在相同的era之内,而不是在相同的year之内,因为两个日期自然可能属于不同的年份。

用法

let yesterday = Date(timeInterval: -86400, since: Date())
let tomorrow = Date(timeInterval: 86400, since: Date())


let diff = tomorrow.interval(ofComponent: .day, fromDate: yesterday)
// return 2
Vinod Vishwanath answered 2020-07-26T04:46:42Z
18 votes

Swift 4版本

let startDate = "2000-11-22"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let formatedStartDate = dateFormatter.date(from: startDate)
let currentDate = Date()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
let differenceOfDate = Calendar.current.dateComponents(components, from: formatedStartDate!, to: currentDate)

print (differenceOfDate)

印刷-年:16个月:10天:19小时:12分钟:16秒:42 isLeapMonth:假

swift4日历日期

Steve B answered 2020-07-26T04:47:11Z
12 votes

如果有人要这样做,请按照以下步骤操作

1.添加此日期扩展

extension Date {
    /// Returns the amount of years from another date
func years(from date: Date) -> Int {
    return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
}
/// Returns the amount of months from another date
func months(from date: Date) -> Int {
    return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
/// Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
    return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
/// Returns the amount of days from another date
func days(from date: Date) -> Int {
    return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
/// Returns the amount of hours from another date
func hours(from date: Date) -> Int {
    return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
/// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
    return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
/// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
    return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
/// Returns the amount of nanoseconds from another date
func nanoseconds(from date: Date) -> Int {
    return Calendar.current.dateComponents([.nanosecond], from: date, to: self).nanosecond ?? 0
}
/// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
    var result: String = ""
            if years(from: date)   > 0 { return "\(years(from: date))y"   }
            if months(from: date)  > 0 { return "\(months(from: date))M"  }
            if weeks(from: date)   > 0 { return "\(weeks(from: date))w"   }
    if seconds(from: date) > 0 { return "\(seconds(from: date))" }
            if days(from: date)    > 0 { result = result + " " + "\(days(from: date)) D" }
            if hours(from: date)   > 0 { result = result + " " + "\(hours(from: date)) H" }
            if minutes(from: date) > 0 { result = result + " " + "\(minutes(from: date)) M" }
           if seconds(from: date) > 0 { return "\(seconds(from: date))" }
    return ""
 }
}

2.在全球范围内定义

 fileprivate var timer: Timer?

3.在viewDidLoad或任何需要的地方调用此方法

override func viewDidLoad() {
    super.viewDidLoad()
    self.getRemainingTime()
} 

4.用途

fileprivate func getRemainingTime() {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let startDate = "2018-06-02 10:11:12"
    let currentDate = dateFormatter.string(from: Date())

    if currentDate != startDate {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(calculateTime)), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
        timer?.fire()
    }
    else {
        self.timer?.invalidate()
        self.timer = nil
    }
}

func calculateTime() {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let stdate : String = "2018-06-02 10:11:12"
    let startDate = dateFormatter.date(from: stdate)!

    let currentDate = Date()

    let strTimer : String = startDate.offset(from: currentDate)
    if !strTimer.isEmpty {
        let stDay: String = "\((Int(strTimer)! % 31536000) / 86400)"
        let stHour: String = "\((Int(strTimer)! % 86400) / 3600)"
        let stMin: String = "\((Int(strTimer)! % 3600) / 60)"
        let stSec: String = "\(Int(strTimer)! % 60)"
        yourLabelOutlet.text = "Start In :\(stDay) Days \(stHour) Hours \(stMin) Minutes \(stSec) Seconds"
    }

}

就像魅力一样工作您可以在UI端使用每个单独的字符串,请享用

iTALIYA answered 2020-07-26T04:47:52Z
8 votes
private func calculateDaysBetweenTwoDates(start: Date, end: Date) -> Int {

    let currentCalendar = Calendar.current
    guard let start = currentCalendar.ordinality(of: .day, in: .era, for: start) else {
        return 0
    }
    guard let end = currentCalendar.ordinality(of: .day, in: .era, for: end) else {
        return 0
    }
    return end - start
}
Kevin answered 2020-07-26T04:48:08Z
7 votes

在Swift4中,我们可以使用以下代码轻松获得两个不同日历日期之间的天数。

第一个是与当前日期的天数差异。

let previousDate = "2017-03-01"
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let previousDateFormated : Date? = dateFormatter.date(from: previousDate)
let difference = currentDate.timeIntervalSince(previousDateFormated!)
var differenceInDays = Int(difference/(60 * 60 * 24 ))
print(differenceInDays)

继续上面的代码...下面是查找两个不同日期的天数。 前一日期的内容取自上述日期

let futureDate = "2017-12-30"
let futureDateFormatted : Date? = dateFormatter.date(from: futureDate)
differenceInDays = (futureDateFormatted?.timeIntervalSince(previousDateFormated!))! / (60 * 60 * 24)

print(differenceInDays)
Ashim Dahal answered 2020-07-26T04:48:37Z
2 votes

在另一个线程上找到了这个,但是对于我来说,它最终是使用Swift 4最简单的解决方案:

let previousDate = ENTER DATE HERE
let now = Date()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief // May delete the word brief to let Xcode show you the other options
formatter.allowedUnits = [.month, .day, .hour]
formatter.maximumUnitCount = 1   // Show just one unit (i.e. 1d vs. 1d 6hrs)

let stringDate = formatter.string(from: previousDate, to: now)
Coltuxumab answered 2020-07-26T04:48:57Z
2 votes

如果有人需要显示所有时间单位,例如“小时分钟秒”,而不仅仅是“小时”。 假设两个日期之间的时差为1小时59分钟20秒。 此功能将显示“ 1h 59m 20s”。

这是我的代码:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"
let start = dateFormatter.date(from: "2019-01-31T07:45:00")!
let end = dateFormatter.date(from: "2019-03-01T06:30:00")!
print("Date Difference :   ", end.offsetFrom(date: start))

功能定义:

extension Date {

    func offsetFrom(date : Date) -> String {

        let dayHourMinuteSecond: Set = [.day, .hour, .minute, .second]
        let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: self);

        let seconds = "\(difference.second ?? 0)s"
        let minutes = "\(difference.minute ?? 0)m" + " " + seconds
        let hours = "\(difference.hour ?? 0)h" + " " + minutes
        let days = "\(difference.day ?? 0)d" + " " + hours

        if let day = difference.day, day          > 0 { return days }
        if let hour = difference.hour, hour       > 0 { return hours }
        if let minute = difference.minute, minute > 0 { return minutes }
        if let second = difference.second, second > 0 { return seconds }
        return ""
    }
}
Meet Doshi answered 2020-07-26T04:49:25Z
1 votes
import Foundation

extension DateComponents {

    func dateComponentsToTimeString() -> String {

        var hour = "\(self.hour!)"
        var minute = "\(self.minute!)"
        var second = "\(self.second!)"

        if self.hour! < 10 { hour = "0" + hour }
        if self.minute! < 10 { minute = "0" + minute }
        if self.second! < 10 { second = "0" + second }

        let str = "\(hour):\(minute):\(second)"
        return str
    }

}

extension Date {

    func offset(from date: Date)-> DateComponents {
        let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
        let differenceOfDate = Calendar.current.dateComponents(components, from: date, to: self)
        return differenceOfDate
    }
}

用:

 var durationString: String {
        return self.endTime.offset(from: self.startTime).dateComponentsToTimeString()
    }
Mohammad Razipour answered 2020-07-26T04:49:45Z
0 votes
private func days(actual day1:[Int],expect day2:[Int]) -> Int {

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

        let first = "\(day1[2])-\(day1[1])-\(day1[0])"
        let firstDate = dateFormatter.date(from:first)!
        let last = "\(day2[2])-\(day2[1])-\(day2[0])"
        let lastDate = dateFormatter.date(from:last)!

        let currentCalendar = NSCalendar.current

        let components = currentCalendar.dateComponents([.day], from: firstDate, to: lastDate)

        return components.day!
    }

与日月年的组成部分比较的另一种方法

用法:

以以下格式输入日期

[dd, mm, yyyy]
[9, 6, 2017]
[6, 6, 2017]
Anuj Panwar answered 2020-07-26T04:50:13Z
0 votes

为Swift 3更新:

如果要打印两个日历日期之间的天数以及天数列表,请使用以下简单代码;

//变量声明:

var daysListArray = [String]()

//函数定义:

func printCountBtnTwoDates(mStartDate: Date, mEndDate: Date) -> Int {
    let calendar = Calendar.current
    let formatter = DateFormatter()
    var newDate = mStartDate
    daysListArray.removeAll()

    while newDate <= mEndDate {
        formatter.dateFormat = "yyyy-MM-dd"
        daysListArray.append(formatter.string(from: newDate))
        newDate = calendar.date(byAdding: .day, value: 1, to: newDate)!
    }
   // print("daysListArray: \(daysListArray)") // if you want to print list between start date and end date
    return daysListArray.count
}

//调用上述函数:

    let count = self.printCountBtnTwoDates(mStartDate: your_start_date, mEndDate: your_end_date)
    print("count: \(count)") // date count

//享受编码...!

Kiran jadhav answered 2020-07-26T04:50:55Z
translate from https://stackoverflow.com:/questions/40075850/swift-3-find-number-of-calendar-days-between-two-dates