i can select time at date picker when i get value from that in UTC so how to convert UTC time to GMT+05:30 to date?

我只是一个虾纸丫 提交于 2019-11-30 06:11:44

问题


var timeReminder = Date()
let dateFormReminder = DateFormatter()
dateFormReminder.calendar = Calendar.current
dateFormReminder.dateFormat = "HH:mm a"
dateFormReminder.timeZone = TimeZone(abbreviation: "GMT +05:30")
timeReminder = dateFormReminder.date(from: txt_time.text!)!

Image of date picker

i am not get local time when i am convert time string to date value. OUTPUT:- 2000-01-01 07:12:00 +0000


回答1:


You need to do like this

UIDatePicker display Local DateTime but it returns UTC DateTime. So you need to convert it to Local for getting actual Local Date and time.

func GetLocalStringDateFromUTC(date:Date)-> String{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" //Your date format
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+5:30") //Current time zone different
    let myString = dateFormatter.string(from: date) //according to date format your date string
    return myString //Convert String to Date
}

// For Get date from string
func GetDateFromString(date_string:String,dateFormat:String)-> Date{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat //Your date format
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
    let date = dateFormatter.date(from: date_string) //according to date format your date string
    return date! //Convert String to Date
}

// For Get time from Date
func GetTimefromDate(date_string:String,dateFormat:String)-> String{

    let dateFormatter_db = DateFormatter()
    dateFormatter_db.dateFormat = dateFormat
    let dateFormatter_eventDate = DateFormatter()
    dateFormatter_eventDate.dateFormat = "hh:mm a" //Your time format
    let date = dateFormatter_db.date(from: date_string)
    return dateFormatter_eventDate.string(from: date!)
}

Use like this

let date = datePicker.date  // Pass your DatePicker Date Here

print(GetLocalStringDateFromUTC(date: date)) // Local String Date from UTC
print(GetDateFromString(date_string: GetLocalStringDateFromUTC(date: date), dateFormat: "yyyy-MM-dd HH:mm:ss")) // Local Date() from UTC
print(self.GetTimefromDate(date_string: self.GetLocalStringDateFromUTC(date: datePicker.date), dateFormat: "yyyy-MM-dd HH:mm:ss")) // Local Time from UTC

Output:



来源:https://stackoverflow.com/questions/52475914/i-can-select-time-at-date-picker-when-i-get-value-from-that-in-utc-so-how-to-con

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