将日期从一种格式转换为另一种格式 [英] Convert Date from one format to another

查看:55
本文介绍了将日期从一种格式转换为另一种格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将日期从一种格式转换为另一种格式.但是下面代码中的日期是零.你们能帮我看看下面的代码吗.

I trying to convert date from one format to another. But the date in the below code is coming as nil. Can you guys help me out below is the code.

   func eventTimeDate() -> Date {
        let dtf = DateFormatter()
        dtf.timeZone = TimeZone.current
        dtf.dateFormat = "yyyy-MM-dd HH:mm:ss z" 

        /// "2020-05-28 00:20:00 GMT+5:30"   
        let stringDate = dtf.string(from: self)

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"

        /// nil
        let date = dateFormatter.date(from: stringDate)

        return date!
    }

推荐答案

您的代码中存在三个问题.首先,在解析固定日期格式时,您应该始终将日期格式化程序的语言环境设置为en_US_POSIX".其次,您需要转义日期字符串的 GMT.最后但并非最不重要的一点是,您需要修复时区字符串,该字符串缺少时区小时的前导零:

You have three problems in your code. First when parsing a fixed date format you should always set the date formatter's locale to "en_US_POSIX". Second you need to escape the GMT of your date string. Last but not least important you need to fix your timezone string which it is missing the leading zero for your timezone hour:

let dateStr = "2020-05-28 00:20:00 GMT+5:30"
let formatter = DateFormatter()
// set the date formatter's locale to "en_US_POSIX"
formatter.locale = .init(identifier: "en_US_POSIX")
// escape the GMT of your date string
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'GMT'Z"
// add the leading zero for your timezone hour
let string = dateStr.replacingOccurrences(of: "(GMT[+-])(\\d:)", with: "$10$2", options: .regularExpression)
if let date = formatter.date(from: string) {
    print(date)  // "2020-05-27 18:50:00 +0000\n"
}

这篇关于将日期从一种格式转换为另一种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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