你需要这样做
UIDatePicker
显示本地日期时间,但它返回 UTC 日期时间。因此,您需要将其转换为本地以获取实际的本地日期和时间。
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!)
}
像这样使用
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
输出: