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

日期选择器的图像

在此处输入图像描述

当我将时间字符串转换为日期值时,我没有得到当地时间。输出:- 2000-01-01 07:12:00 +0000

4

1 回答 1

2

你需要这样做

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

输出:

在此处输入图像描述

于 2018-09-24T11:06:51.107 回答