首页 > 解决方案 > Swift 中有 PrettyTime 函数吗

问题描述

在我的 android 应用程序中,我使用以下代码获取将日期转换为可读句子的字符串(见下图)。swift 4.2有什么方法可以做到这一点吗?

 private String getDate(String d) {

    String datemobile = "";
    try {
        String section1 = null;
        String mydateStr = null;
        DateFormat df1 = null;
        PrettyTime p = new PrettyTime();
        Date date = null;

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        df1 = new SimpleDateFormat("EEE, d MMM yyyy ");
        date = df.parse(d);
        mydateStr = df1.format(date);


        datemobile = p.format(date) + " on " + mydateStr;
        return datemobile;

    } catch (Exception e) {
        e.printStackTrace();

        return datemobile;
    }
}

在此处输入图像描述

标签: iosswiftxcodensdateprettytime

解决方案


尝试这个 ,

    let startDateString = "03/01/2019" // start date
    let endDateString = "15/03/2019" // end date

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    let startDate = dateFormatter.date(from: startDateString)
    let endDate = dateFormatter.date(from: endDateString)

    let gregorian = NSCalendar(calendarIdentifier:NSCalendar.Identifier.gregorian)

    let c2 = gregorian?.components([.minute, .hour, .weekOfMonth , .day, .month, .year], from: startDate!, to: endDate!, options: .matchFirst)
    print(c2)

参考: https ://developer.apple.com/documentation/foundation/nscalendar/unit

输出:

在此处输入图像描述


推荐阅读