美文网首页
Swift时间戳转换为字符串及动态发布日期转换

Swift时间戳转换为字符串及动态发布日期转换

作者: 凯司机 | 来源:发表于2021-03-20 18:05 被阅读0次

1.时间戳分类

extension TimeInterval {

    // 把秒数转换成时间的字符串

    funcconvertString() ->String{

        // 把获取到的秒数转换成具体的时间

        letcreateDate =Date(timeIntervalSince1970:self)

        // 获取当前日历

        letcalender =Calendar.current

        // 获取日期的年份

        letcomps = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: createDate, to:Date())

        // 日期格式

        letformatter =DateFormatter()

        // 判断当前日期是否为今年

        guardcreateDate.isThisYear()else{

            formatter.dateFormat="yyyy-MM-dd HH:mm:ss"

            returnformatter.string(from: createDate)

        }

        // 是否是前天

        ifcreateDate.isBeforeYesterday() {

            formatter.dateFormat="前天 HH:mm"

            returnformatter.string(from: createDate)

        }elseifcreateDate.isToday()||createDate.isYesterday() {

            // 判断是否是今天或者昨天

            ifcomps.hour!>=1{

                returnString(format:"%d小时前", comps.hour!)

            }elseifcomps.minute!>=1{

                returnString(format:"%d分钟前", comps.minute!)

            }else{

                return"刚刚"

            }

        }else{

            formatter.dateFormat="MM-dd HH:mm"

            returnformatter.string(from: createDate)

        }

    }

}

2.Date的分类

extension Date {

    /// 判断当前日期是否为今年

    funcisThisYear() ->Bool{

        // 获取当前日历

        letcalender =Calendar.current

        // 获取日期的年份

        letyearComps = calender.component(.year, from:self)

        // 获取现在的年份

        letnowComps = calender.component(.year, from:Date())

        returnyearComps==nowComps

    }

    ///是否是昨天

    funcisYesterday() ->Bool{

        // 获取当前日历

        letcalender =Calendar.current

        // 获取日期的年份

        letcomps = calender.dateComponents([.year, .month, .day], from:self, to:Date())

        // 根据头条显示时间 ,我觉得可能有问题 如果comps.day == 0 显示相同,如果是 comps.day == 1 显示时间不同

        // 但是 comps.day == 1 才是昨天 comps.day == 2 是前天

//        return comps.year == 0 && comps.month == 0 && comps.day == 1

        returncomps.year==0&&comps.month==0&&comps.day==0

    }

    ///是否是前天

    func isBeforeYesterday() -> Bool {

        // 获取当前日历

        letcalender =Calendar.current

        // 获取日期的年份

        letcomps = calender.dateComponents([.year, .month, .day], from:self, to:Date())

        //

//        return comps.year == 0 && comps.month == 0 && comps.day == 2

        returncomps.year==0&&comps.month==0&&comps.day==1

    }

    /// 判断是否是今天

    funcisToday() ->Bool{

        // 日期格式化

        letformatter =DateFormatter()

        // 设置日期格式

        formatter.dateFormat="yyyy-MM-dd"

        letdateStr = formatter.string(from:self)

        letnowStr = formatter.string(from:Date())

        returndateStr==nowStr

    }

}

相关文章

网友评论

      本文标题:Swift时间戳转换为字符串及动态发布日期转换

      本文链接:https://www.haomeiwen.com/subject/pnbwcltx.html