Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

swift - 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?

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

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...