NSDateFormatter relative date formatting with custom format

前端 未结 3 2341
再見小時候
再見小時候 2021-02-19 23:18

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

3条回答
  •  故里飘歌
    2021-02-19 23:54

    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
        }
    }
    

提交回复
热议问题