string to date in my timeZone make wrong date

风流意气都作罢 提交于 2020-01-06 05:35:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!