如何在日期格式中添加 th 和 st [英] How to add th and st in Date Format

查看:166
本文介绍了如何在日期格式中添加 th 和 st的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将日期转换为星期五 17 日下午 7:00" 这种格式.但我无法在日期后添加th"和st".我正在使用下面的代码来转换这样的日期格式.请告诉我.我为这种格式做什么?

I want to convert the date like "Friday 17th, 7:00pm" this format. but I am unable to add "th" and "st" after the date. I am using below code to convert the date format like this. please tell me. What I do for this format?

 func convertDateFormater(_ date: String) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        //dateFormatter.locale = Locale(identifier: "your_loc_id")
        let convertedDate = dateFormatter.date(from: date)
        guard dateFormatter.date(from: date) != nil else {
            assert(false, "no date from string")
            return ""
        }
        dateFormatter.dateFormat = "EEEE dd, h:mma"///this is what you want to convert format
        dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        let timeStamp = dateFormatter.string(from: convertedDate!)

        return timeStamp
    }

推荐答案

只要不同的语言环境不发挥任何作用,您可以执行以下操作:

As long as different locales do not play any role you could do something like this:

let date = Date()

let calendar = Calendar.current

let day = calendar.component(.day, from: date)
let daySuffix: String

switch day {
case 11...13: return "th"
default:
    switch day % 10 {
    case 1: return "st"
    case 2: return "nd"
    case 3: return "rd"
    default: return "th"
    }
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE dd'\(daySuffix)', h:mma"

dateFormatter.string(from: date)

这篇关于如何在日期格式中添加 th 和 st的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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