在特定的日期和时间以快速的时间获取UTC时间? [英] Get UTC time for a particular date and time in swift?
问题描述
Helllo all,
Helllo all,
我有一个特定的日期&在iOS中从datepicker中选择的时间。我想转换这个日期&时间到UTC时间。我已经使用了下面的功能。
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.
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!)
}
我的位置在印度。所以当我通过时间像 2016-12-26 09:53:45
然后它给我UTC时间作为 2016-12-26 15:23 :00 +0530
。现在我在谷歌搜索UTC时间,显示时间为 4:32 AM 26十二月
。请告诉为什么这种差异我正在做正确的事情吗?
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 ?
推荐答案
你可以尝试使用以下代码:
因为根据我的理解,你应该提供您的本地时区首先将您的日期转换为本地,然后将其转换为UTC:
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:
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!)
}
timeZone code.Check,让我知道如果没有解决
I replaced timeZone code.Check and let me know if not solved
这篇关于在特定的日期和时间以快速的时间获取UTC时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!