简体   繁体   English

将日期转换为格林尼治标准时间(GMT)时间日期日期月年Swift

[英]Convert date to GMT time of Day Date Month Year Swift

I'm struct on how to get/convert current time to GMT time in format "Wed, 08 Apr 2015 21:27:30 GMT" 我将以“星期三,2015年4月8日21:27:30 GMT”格式获取如何将当前时间转换为格林尼治标准时间的信息

Currently I'm using below code to convert but that gives me "Wednesday" instead of "Wed" , "April" instead of "Apr" and most importantly in current local time. 目前,我正在使用下面的代码进行转换,但是这给了我“星期三”而不是“星期三”,“ April”而不是“ Apr”,最重要的是在当前本地时间。

Please advice how to get current GMT time in below format "Wed, 08 Apr 2015 21:27:30 GMT" 请以以下格式“ 2015年4月8日星期三,格林尼治标准时间”建议如何获取当前格林尼治标准时间。

func convertDateToDayDateMonthYear(from inputFormat: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = inputFormat
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")

    if let dateInLocal = dateFormatter.date(from: self) {
        dateFormatter.dateFormat = "EEEE, dd MMMM yyyy"
        dateFormatter.locale = Locale.current
        return dateFormatter.string(from: dateInLocal)
    }

    return "NA"
}

Use date formatter as 使用日期格式器作为

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
print(dateFormatter.string(from: date))

Console o/p 控制台o / p

Tue, 10 Sep 2019 16:01:13 GMT Tue,10 Sep 2019 16:01:13 GMT

Follow this link to learn more about date formatting styles 单击此链接以了解有关日期格式样式的更多信息

Your dateFormatter.dateFormat is incorrect. 您的dateFormatter.dateFormat不正确。 Check this site to structure it the way you like: https://nsdateformatter.com/ 检查此站点以按照您喜欢的方式进行构建: https : //nsdateformatter.com/

This site will let you test out different formats without actually having to run code. 这个站点可以让您测试不同的格式,而无需实际运行代码。 This way, you'll be able to experiment and find the dateFormat that is best for your code. 这样,您就可以进行实验并找到最适合您的代码的dateFormat。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM