xcode 快速获取特定日期和时间的UTC时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41326460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get UTC time for a particular date and time in swift?
提问by TechChain
Helllo all,
大家好,
I have a particular date & time selected from datepicker in iOS. i want to convert this date & time into UTC time.I have used below function for it.
我从 iOS 中的日期选择器中选择了一个特定的日期和时间。我想将此日期和时间转换为 UTC 时间。我为此使用了以下函数。
func get_Date_time_from_UTC_time(string : String) -> String {
let dateformattor = DateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC") as TimeZone!
let dt = string
let dt1 = dateformattor.date(from: dt as String)
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateformattor.timeZone = NSTimeZone.local
return dateformattor.string(from: dt1!)
}
My location is in india. So when i pass time like 2016-12-26 09:53:45
then it gives me UTC time as 2016-12-26 15:23:00 +0530
.Now when i search in google for UTC time it shows me time as 4:32 AM 26 december
.Please tell why is such diffrence & am i doing correct ?
我的位置在印度。因此,当我像那样打发时间时,2016-12-26 09:53:45
它给了我 UTC 时间2016-12-26 15:23:00 +0530
。现在,当我在谷歌搜索 UTC 时间时,它显示我的时间4:32 AM 26 december
是
采纳答案by Dheeraj D
Could you please try using below code: Because as per my understanding you should provide your local time zone first to convert your date into local and then it will convert into UTC:
您能否尝试使用以下代码:因为根据我的理解,您应该首先提供您的本地时区以将您的日期转换为本地,然后它将转换为 UTC:
func get_Date_time_from_UTC_time(string : String) -> String {
let dateformattor = DateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateformattor.timeZone = NSTimeZone.local
let dt = string
let dt1 = dateformattor.date(from: dt as String)
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC") as TimeZone!
return dateformattor.string(from: dt1!)
}
I replaced timeZone code.Check and let me know if not solved
我替换了 timeZone 代码。检查并让我知道如果没有解决
回答by Bista
This is because you are treating the date passed in parameter as UTC timezone, and asking it to be converted into Local Timezone. Instead you meant the opposite.
这是因为您将传入参数的日期视为 UTC 时区,并要求将其转换为本地时区。相反,你的意思正好相反。
func get_Date_time_from_UTC_time(string : String) -> String {
let dateformattor = DateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateformattor.timeZone = NSTimeZone.local
let dt = string
let dt1 = dateformattor.date(from: dt as String)
dateformattor.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC") as TimeZone!
return dateformattor.string(from: dt1!)
}