我的timeZone中的日期字符串错误的日期

时间:2018-08-02 11:58:45

标签: swift time nsdateformatter formatter

我正在尝试将String转换为我所在国家时区的日期,但结果不像以前那样格式化

   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
打印行中的

日期正确,但是时间不正确。我需要时间到我的时间选择器

更新:

当我更改时间时,我有时间监听器,请在textField上设置值

如下所示:

   self.timePickerFrom.addTarget(self, action: #selector(self.dateChangedFrom(_:)), for: .valueChanged).  // the listener

这就是我为改变价值而做的事情:

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)"

但是问题是当我改变分钟数时会向前移动30分钟

1 个答案:

答案 0 :(得分:1)

您的操作方式有误,您应该在日期选择器上设置格式,而不是日期选择器的date

看下面的代码:

@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
}

sample

是你的意思吗?

我刚刚上传了一个示例项目,您可以在这里查看它:sample project