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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…