Swift days between two NSDates

后端 未结 27 1516
清歌不尽
清歌不尽 2020-11-27 13:30

I\'m wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the \"new\" Cocoa?

E.g. like in Ruby I would do:

27条回答
  •  情歌与酒
    2020-11-27 13:33

    extension Date {
        func daysFromToday() -> Int {
            return Calendar.current.dateComponents([.day], from: self, to: Date()).day!
        }
    }
    

    Then use it like

        func dayCount(dateString: String) -> String{
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMM dd,yyyy hh:mm a"
            let fetchedDate = dateFormatter.date(from: dateString)
    
    
            let day = fetchedDate?.daysFromToday()
            if day! > -1{
                return "\(day!) days passed."
            }else{
            return "\(day! * -1) days left."
            }
        }
    

提交回复
热议问题