MMM dd,yyyy hh:mm:ss a的正确date.format是什么?以及如何转换为dd-mm-yyyy HH:ii [英] What is the correct date.format for MMM dd, yyyy hh:mm:ss a? and how convert to dd-mm-yyyy HH:ii

查看:177
本文介绍了MMM dd,yyyy hh:mm:ss a的正确date.format是什么?以及如何转换为dd-mm-yyyy HH:ii的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下内容转换为 2017年12月31日晚上8:00 ,在Swift 4中转换为 dd-mm-yyyy HH:ii 格式。

I want convert this: Dec 31, 2017 8:00:00 PM to dd-mm-yyyy HH:ii format in Swift 4.

这是我到目前为止的代码:

This is my code so far:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM dd, yyyy hh:mm:ss a"//this your string date format

    if let translatedDate = dateFormatter.date(from: datetime) {
        dateFormatter.dateFormat = "dd-MM-yyyy HH:ii"
        return dateFormatter.string(from: translatedDate)
    }

该代码永远不会输入if语句中。我想我的日期格式不正确。

The code never enters in the if statement. I guess my date format is not correct.

推荐答案

A DateFormatter 可在日期及其文本表示形式之间进行转换。

A DateFormatter that converts between dates and their textual representations.

您可以找到更多的语言环境标识符此处

You can find more Locale identifier here.


  • 首先,将日期转换为本地时区。在可以隐瞒特定格式的日期之后,使用 Locale


并尝试以下代码。

let dateStr = "Wed, 26 Jul 2017 18:10:02 +0530"
if let date = Date(fromString: dateStr, format: "MMM dd, yyyy hh:mm:ss a") {
        debugPrint(date.toString(format: "dd-MM-yyyy HH:ii"))
}

日期扩展是...

extension Date {

    // Initializes Date from string and format
    public init?(fromString string: String, format: String, identifier: String = Locale.current.identifier) {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.locale = Locale(identifier: identifier)
        if let date = formatter.date(from: string) {
            self = date
        } else {
            return nil
        }
    }

    // Converts Date to String, with format
    public func toString(format: String, identifier: String = Locale.current.identifier) -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: identifier)
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

字符串扩展名是...

extension String {
    // Converts String to formated date string, with inputFormat and outputFormat
    public func toDate(form inputFormat: String, to outputFormat: String, identifier: String = Locale.current.identifier) -> String? {
        return Date(fromString: self, format: inputFormat, identifier: identifier)?.toString(format: outputFormat, identifier: identifier)
    }

    // Converts String to Date, with format
    func toDate(format: String, identifier: String = Locale.current.identifier) -> Date? {
        return Date(fromString: self, format: format, identifier: identifier)
    }
}

这篇关于MMM dd,yyyy hh:mm:ss a的正确date.format是什么?以及如何转换为dd-mm-yyyy HH:ii的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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