问题
I'm trying to convert String to date in my country time zone but the result is not as formatted I did
let dbl = TimeInterval(longDate)
let date = Date(timeIntervalSince1970: dbl / 1000)
let formatter = DateFormatter()
print(longDate)
formatter.calendar = Calendar(identifier: .persian)
formatter.locale = Locale(identifier: "fa_IR")
formatter.timeZone = TimeZone(identifier: "IRST")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let a = formatter.string(from: date)
resultDate = dateFormatter.date(from: a)
print(reslutDate,a) //2018-08-02 11:56:28 +0000 incorrect time 1397-05-11 15:56:28 correct time
in print line date is correct but the time is incorrect. I need this time to my Timepicker
update :
I have listener for time when I change the time set the value on textField
like below :
self.timePickerFrom.addTarget(self, action: #selector(self.dateChangedFrom(_:)), for: .valueChanged). // the listener
and this is what I do for changing value :
let date = self.timePickerFrom.date
print(date)
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
let hour = components.hour!
let minute = components.minute!
self.timeOfloadingLable.text = "\(hour):\(minute)"
but the problem is when I change minute goes 30Min forward
回答1:
Your are doing it in wrong way, You should set format on date picker not the date
of date picker.
Look at this code:
@IBOutlet weak var epoch: UITextField!
@IBOutlet weak var dateTimePicker: UIDatePicker!
@IBAction func presentDate(_ sender: UIButton) {
guard let text = epoch.text else {return}
guard let epoch = Double(text) else {return}
guard let date = convertDate(epoch: epoch) else {return}
dateTimePicker.date = date
dateTimePicker.timeZone = TimeZone(identifier: "IRST")
dateTimePicker.locale = Locale(identifier: "fa_IR")
dateTimePicker.calendar = Calendar(identifier: Calendar.Identifier.persian)
}
private func convertDate(epoch: Double) -> Date? {
let date = Date(timeIntervalSince1970: epoch)
return date
}
Is it what you mean?
I just uploaded a sample project, you can check it here: sample project
来源:https://stackoverflow.com/questions/51653088/string-to-date-in-my-timezone-make-wrong-date