Swift convert time to time ago

前端 未结 13 1206
一个人的身影
一个人的身影 2020-12-24 02:14

In Swift5, we have RelativeDateTimeFormatter

Prior to Swift5:


I\'m trying to convert time to time ago, what i wanna do is:

from 1

相关标签:
13条回答
  • 2020-12-24 02:54

    Swift 4 version of truongky's code:

    And Add Optional for TimeEnd not now.

    extension Date {
    
        func getElapsedInterval(to end: Date = Date()) -> String {
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.year], from: self, to: end).day {
                if interval > 0 {
                    return "\(interval) year\(interval == 1 ? "":"s")"
                }
            }
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.month], from: self, to: end).month {
                if interval > 0 {
                    return "\(interval) month\(interval == 1 ? "":"s")"
                }
            }
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.weekOfMonth], from: self, to: end).weekOfMonth {
                if interval > 0 {
                    return "\(interval) week\(interval == 1 ? "":"s")"
                }
            }
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.day], from: self, to: end).day {
                if interval > 0 {
                    return "\(interval) day\(interval == 1 ? "":"s")"
                }
            }
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.hour], from: self, to: end).hour {
                if interval > 0 {
                    return "\(interval) hour\(interval == 1 ? "":"s")"
                }
            }
    
            if let interval = Calendar.current.dateComponents([Calendar.Component.minute], from: self, to: end).minute {
                if interval > 0 {
                    return "\(interval) minute\(interval == 1 ? "":"s")"
                }
            }
    
            return "Just now."
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题