Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

前端 未结 19 2059
时光说笑
时光说笑 2020-11-22 02:16

I am trying to get the difference between the current date as NSDate() and a date from a PHP time(); call for example: NSDate(timeIntervalSin

19条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:47

    --> Use this to find time gap between two dates in Swift(With two Strings).

    func timeGapBetweenDates(previousDate : String,currentDate : String)
    {
        let dateString1 = previousDate
        let dateString2 = currentDate
    
        let Dateformatter = DateFormatter()
        Dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    
        let date1 = Dateformatter.date(from: dateString1)
        let date2 = Dateformatter.date(from: dateString2)
    
    
        let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
        let secondsInAnHour: Double = 3600
        let minsInAnHour: Double = 60
        let secondsInDays: Double = 86400
        let secondsInWeek: Double = 604800
        let secondsInMonths : Double = 2592000
        let secondsInYears : Double = 31104000
    
        let minBetweenDates = Int((distanceBetweenDates! / minsInAnHour))
        let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
        let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
        let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))
        let monthsbetweenDates = Int((distanceBetweenDates! / secondsInMonths))
        let yearbetweenDates = Int((distanceBetweenDates! / secondsInYears))
        let secbetweenDates = Int(distanceBetweenDates!)
    
    
    
    
        if yearbetweenDates > 0
        {
            print(yearbetweenDates,"years")//0 years
        }
        else if monthsbetweenDates > 0
        {
            print(monthsbetweenDates,"months")//0 months
        }
        else if weekBetweenDates > 0
        {
            print(weekBetweenDates,"weeks")//0 weeks
        }
        else if daysBetweenDates > 0
        {
            print(daysBetweenDates,"days")//5 days
        }
        else if hoursBetweenDates > 0
        {
            print(hoursBetweenDates,"hours")//120 hours
        }
        else if minBetweenDates > 0
        {
            print(minBetweenDates,"minutes")//7200 minutes
        }
        else if secbetweenDates > 0
        {
            print(secbetweenDates,"seconds")//seconds
        }
    }
    

提交回复
热议问题