当前位置:  开发笔记 > 编程语言 > 正文

Swift转换不久前

如何解决《Swift转换不久前》经验,为你挑选了4个好方法。

我正在尝试不时转换,我想做的是:

从1到15秒它会说"刚才"

从60分钟到119分钟它会说"一小时前"

从24小时到47小时它会说"昨天"

从7天到7天23小时,它会说"一周前"

我不知道我的计数,如果我错了,请随时为我解决

这是代码

    extension NSDate {

    struct Date {
        static let timeFormatter: NSDateFormatter = {
            let df = NSDateFormatter()
            df.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
            df.dateFormat = "h:mm a"
            return df
            }()
    }
    var time: String { return Date.timeFormatter.stringFromDate(self) }

    var year:    Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Year,   fromDate: self) }
    var month:   Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Month,  fromDate: self) }
    var day:     Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Day,    fromDate: self) }
    var hour:     Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Hour,    fromDate: self) }
    var minute:     Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Minute,    fromDate: self) }
    var second:     Int { return NSCalendar.autoupdatingCurrentCalendar().component(.Second,    fromDate: self) }


    struct DateComponents {
        static let formatter: NSDateComponentsFormatter = {
            let dcFormatter = NSDateComponentsFormatter()
            dcFormatter.calendar = NSCalendar(identifier: NSCalendarIdentifierISO8601)!
            dcFormatter.unitsStyle = .Full
            dcFormatter.maximumUnitCount = 1
            dcFormatter.zeroFormattingBehavior = .Default
            dcFormatter.allowsFractionalUnits = false
            dcFormatter.allowedUnits = [.Year, .Month, .Weekday, .Day, .Hour, .Minute, .Second]
            return dcFormatter
            }()
    }

    var elapsedTime: String {


        if isecond(NSDate()) {
            return "Just now"

        }

        if ishour(NSDate()) {
           return "an hour ago"

        }
        if isyesterday(NSDate()) {
            return "Yesterday"
        }
        if isweek(NSDate()) {

            return "a week ago"
        }




        return (DateComponents.formatter.stringFromTimeInterval(NSDate().timeIntervalSinceDate(self)) ?? "") + " ago"
    }
    func isyesterday(date: NSDate) -> Bool {
        return  NSCalendar.autoupdatingCurrentCalendar().isDate(self, inSameDayAsDate: date.yesterday)
    }
    var yesterday: NSDate {
        return  NSCalendar.autoupdatingCurrentCalendar().dateWithEra(1, year: year, month: month, day: day-1, hour: 0, minute: 0, second: 0, nanosecond: 0)!
    }



    func isweek(date: NSDate) -> Bool {
        return  NSCalendar.autoupdatingCurrentCalendar().isDate(self, inSameDayAsDate: date.weekago)
    }
    var weekago: NSDate {
        return  NSCalendar.autoupdatingCurrentCalendar().dateWithEra(1, year: year, month: month, day: day-7, hour: 0, minute: 0, second: 0, nanosecond: 0)!
    }

    func isecond(date: NSDate) -> Bool {
        return  NSCalendar.autoupdatingCurrentCalendar().isDate(self, inSameDayAsDate: date.secondsago)
    }
    var secondsago: NSDate {
        return  NSCalendar.autoupdatingCurrentCalendar().dateWithEra(1, year: year, month: month, day: 0, hour: 0, minute: 0, second: second-15, nanosecond: 0)!
    }

    func ishour(date: NSDate) -> Bool {
        return  NSCalendar.autoupdatingCurrentCalendar().isDate(self, inSameDayAsDate: date.hourago)
    }
    var hourago: NSDate {
        return  NSCalendar.autoupdatingCurrentCalendar().dateWithEra(1, year: year, month: month, day: 0, hour: hour-1, minute: minute-1, second: 0, nanosecond: 0)!
    }
}

这里是我在我的应用程序中得到的: 在此输入图像描述

引用的是"一小时前","刚才"等,没有显示,只有"昨天",我不确定它是否只是7天到23小时!

这是我的第一个问题链接:Swift如何转换Parse createdAt time to time?

请帮我修复代码,感谢@Leo Dabus的代码.



1> Sonia Casas..:

我将更新Truongky对Swif 3的回答:

extension Date {

func getElapsedInterval() -> String {

    let interval = Calendar.current.dateComponents([.year, .month, .day], from: self, to: Date())

    if let year = interval.year, year > 0 {
        return year == 1 ? "\(year)" + " " + "year ago" :
            "\(year)" + " " + "years ago"
    } else if let month = interval.month, month > 0 {
        return month == 1 ? "\(month)" + " " + "month ago" :
            "\(month)" + " " + "months ago"
    } else if let day = interval.day, day > 0 {
        return day == 1 ? "\(day)" + " " + "day ago" :
            "\(day)" + " " + "days ago"
    } else {
        return "a moment ago"

    }

}
}

如果您更喜欢可本地化的响应而不仅仅是英语,那么此代码将完成工作

extension Date {
func getElapsedInterval() -> String {

    var calendar = Calendar.current
    calendar.locale = Locale(identifier: Bundle.main.preferredLocalizations[0]) 
// IF THE USER HAVE THE PHONE IN SPANISH BUT YOUR APP ONLY SUPPORTS I.E. ENGLISH AND GERMAN
// WE SHOULD CHANGE THE LOCALE OF THE FORMATTER TO THE PREFERRED ONE 
// (IS THE LOCALE THAT THE USER IS SEEING THE APP), IF NOT, THIS ELAPSED TIME 
// IS GOING TO APPEAR IN SPANISH

    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.maximumUnitCount = 1
    formatter.calendar = calendar

    var dateString: String?

    let interval = calendar.dateComponents([.year, .month, .weekOfYear, .day], from: self, to: Date())

    if let year = interval.year, year > 0 {
        formatter.allowedUnits = [.year] //2 years
    } else if let month = interval.month, month > 0 {
        formatter.allowedUnits = [.month] //1 month
    } else if let week = interval.weekOfYear, week > 0 {
        formatter.allowedUnits = [.weekOfMonth] //3 weeks
    } else if let day = interval.day, day > 0 {
        formatter.allowedUnits = [.day] // 6 days
    } else {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: Bundle.main.preferredLocalizations[0]) //--> IF THE USER HAVE THE PHONE IN SPANISH BUT YOUR APP ONLY SUPPORTS I.E. ENGLISH AND GERMAN WE SHOULD CHANGE THE LOCALE OF THE FORMATTER TO THE PREFERRED ONE (IS THE LOCALE THAT THE USER IS SEEING THE APP), IF NOT, THIS ELAPSED TIME IS GOING TO APPEAR IN SPANISH
        dateFormatter.dateStyle = .medium
        dateFormatter.doesRelativeDateFormatting = true

        dateString = dateFormatter.string(from: self) // IS GOING TO SHOW 'TODAY'
    }

    if dateString == nil {
        dateString = formatter.string(from: self, to: Date())
    }

    return dateString!
}



2> Sarath Ravee..:

Swift 4+版本

extension Date {

    func timeAgoSinceDate() -> String {

        // From Time
        let fromDate = self

        // To Time
        let toDate = Date()

        // Estimation
        // Year
        if let interval = Calendar.current.dateComponents([.year], from: fromDate, to: toDate).year, interval > 0  {

            return interval == 1 ? "\(interval)" + " " + "year ago" : "\(interval)" + " " + "years ago"
        }

        // Month
        if let interval = Calendar.current.dateComponents([.month], from: fromDate, to: toDate).month, interval > 0  {

            return interval == 1 ? "\(interval)" + " " + "month ago" : "\(interval)" + " " + "months ago"
        }

        // Day
        if let interval = Calendar.current.dateComponents([.day], from: fromDate, to: toDate).day, interval > 0  {

            return interval == 1 ? "\(interval)" + " " + "day ago" : "\(interval)" + " " + "days ago"
        }

        // Hours
        if let interval = Calendar.current.dateComponents([.hour], from: fromDate, to: toDate).hour, interval > 0 {

            return interval == 1 ? "\(interval)" + " " + "hour ago" : "\(interval)" + " " + "hours ago"
        }

        // Minute
        if let interval = Calendar.current.dateComponents([.minute], from: fromDate, to: toDate).minute, interval > 0 {

            return interval == 1 ? "\(interval)" + " " + "minute ago" : "\(interval)" + " " + "minutes ago"
        }

        return "a moment ago"
    }
}

用法

yourDate.timeAgoSinceDate()



3> 小智..:

根据需要更改文本.

extension NSDate {

    func getElapsedInterval() -> String {

        var interval = NSCalendar.currentCalendar().components(.Year, fromDate: self, toDate: NSDate(), options: []).year

        if interval > 0 {
            return interval == 1 ? "\(interval)" + " " + "year" :
            "\(interval)" + " " + "years"
        }

        interval = NSCalendar.currentCalendar().components(.Month, fromDate: self, toDate: NSDate(), options: []).month
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " " + "month" :
            "\(interval)" + " " + "months"
        }

        interval = NSCalendar.currentCalendar().components(.Day, fromDate: self, toDate: NSDate(), options: []).day
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " " + "day" :
            "\(interval)" + " " + "days"
        }

        interval = NSCalendar.currentCalendar().components(.Hour, fromDate: self, toDate: NSDate(), options: []).hour
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " " + "hour" :
            "\(interval)" + " " + "hours"
        }

        interval = NSCalendar.currentCalendar().components(.Minute, fromDate: self, toDate: NSDate(), options: []).minute
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " " + "minute" :
            "\(interval)" + " " + "minutes"
        }

        return "a moment ago"
    }
}



4> rgkobashi..:

Swift 3版的truongky代码:

extension Date {

    var timeAgoSinceNow: String {
        return getTimeAgoSinceNow()
    }

    private func getTimeAgoSinceNow() -> String {

        var interval = Calendar.current.dateComponents([.year], from: self, to: Date()).year!
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " year" : "\(interval)" + " years"
        }

        interval = Calendar.current.dateComponents([.month], from: self, to: Date()).month!
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " month" : "\(interval)" + " months"
        }

        interval = Calendar.current.dateComponents([.day], from: self, to: Date()).day!
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " day" : "\(interval)" + " days"
        }

        interval = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour!
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " hour" : "\(interval)" + " hours"
        }

        interval = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute!
        if interval > 0 {
            return interval == 1 ? "\(interval)" + " minute" : "\(interval)" + " minutes"
        }

        return "a moment ago"
    }
}

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有