swift開發中如何將時間顯示爲幾分鐘前、幾小時前、幾天前、幾個月前

 ///將時間戳轉換爲日期orm

func changeTime(time:Double) -> NSDate {form

        let Time = time/Double(1000)date

        let timeString = NSString(format: "\(Time)")im

        let timeSta:NSTimeInterval = timeString.doubleValue時間戳

        let Startdate = NSDate(timeIntervalSince1970:timeSta)時間

        return Startdateco

    }time

   ///將時間顯示爲(幾分鐘前,幾小時前,幾天前)let

    func compareCurrentTime(str:Double) -> String {return

        //將時間戳轉換爲日期

        let timeDate = self.changeTime(str)

        print(timeDate)

        let currentDate = NSDate()

        let timeInterval = currentDate.timeIntervalSinceDate(timeDate)

        var temp:Double = 0

        var result:String = ""

        if timeInterval/60 < 1 {

             result = "剛剛"

        }else if (timeInterval/60) < 60{

            temp = timeInterval/60

           result = "\(Int(temp))分鐘前"

        }else if timeInterval/60 * 60 < 24 * 60 {

            temp = timeInterval/(60)

            result = "\(Int(temp))小時前"

        }else if timeInterval/(24 * 60 * 60) < 30 * 24 * 60 {

            temp = timeInterval / (24 * 60 * 60)

            result = "\(Int(temp))天前"

        }else if timeInterval/(30 * 24 * 60 * 60)  < 12 * 30 * 24 * 60{

            temp = timeInterval/(30 * 24 * 60 * 60)

            result = "\(Int(temp))個月前"

        }else{

            temp = timeInterval/(12 * 30 * 24 * 60 * 60)

            result = "\(Int(temp))年前"

        }

        return result

    }

相關文章
相關標籤/搜索