NSDateFormatter 使用自定义格式的相对日期格式 [英] NSDateFormatter relative date formatting with custom format

查看:57
本文介绍了NSDateFormatter 使用自定义格式的相对日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的目的是发布如下所示的日期:

So my intention is to put out dates that would look like the following:

Today, August 28
Tomorrow, August 29
Friday, August 30
...etc

问题是我似乎只能靠得这么近.

The issue is that it seems I can only get so close.

当我 setDoesRelativeDateFormatting:YESsetDateStyleFullsetTimeStyleNone 时>,它会产生如下结果:

When I setDoesRelativeDateFormatting:YES and setDateStyle to Full and setTimeStyle to None, it yields results like this:

Today
Tomorrow
Friday, August 30, 2013

这会产生年份,但不会产生今天和明天的月份和日期.

This yields the year and does not yield month and date for today and tomorrow.

我尝试过的其他代码是这样的:

The other code I've tried is this:

[NSDateFormatter dateFormatFromTemplate:@"eeeedMMM" options:0
                                                     locale:[NSLocale currentLocale]];

产生以下结果:

Wednesday, August 28
Thursday, August 29
Friday, August 30

从表面上看,dateStyle 和 timeStyle 或相对日期格式会覆盖自定义格式.

Seemingly, the dateStyle and timeStyle, or the relative date formatting overrides the custom format.

有没有办法在不进行自定义实现的情况下完成这种日期格式?

Is there a way to accomplish this date format without going into a custom implementation?

提前致谢!

推荐答案

我在 Swift 3 中使用这种方法:

I use this approach in Swift 3:

struct SharedFormatters {
    private static let dateWithRelativeFormatting: DateFormatter = {
        let df = DateFormatter()
        df.dateStyle = .medium
        df.doesRelativeDateFormatting = true
        return df
    }()
    private static let dateWithoutRelativeFormatting: DateFormatter = {
        let df = DateFormatter()
        df.dateStyle = .medium
        df.doesRelativeDateFormatting = false
        return df
    }()
    private static let longDateWithoutYear: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "MMMM d"
        df.doesRelativeDateFormatting = false
        return df
    }()
    static func string(from date: Date) -> String {
        let val = dateWithRelativeFormatting.string(from: date)
        let val2 = dateWithoutRelativeFormatting.string(from: date)
        return val == val2 ? longDateWithoutYear.string(from: date) : val
    }
}

这篇关于NSDateFormatter 使用自定义格式的相对日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆