Get UTC time for a particular date and time in swift?

拥有回忆 提交于 2020-01-14 10:32:47

问题


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.

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 ?


回答1:


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!)
  }

I replaced timeZone code.Check and let me know if not solved




回答2:


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.

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!)
}


来源:https://stackoverflow.com/questions/41326460/get-utc-time-for-a-particular-date-and-time-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!