Swift 3 changing date format

江枫思渺然 提交于 2019-12-07 12:37:20

问题


I want to get my Date in DD.MM.YYYY HH:mm:ss as a String.

I use the following extension:

extension Date {
var localTime: String {
    return description(with: Locale.current)
    }
}

and the following code when my datePicker changes:

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
    dateLabel.text = datePicker.date.localTime
    let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy hh:mm"
    let TestDateTime = formatter.date(from: datePicker.date.localTime)
}

What am I doing wrong?


回答1:


Your code is completely wrong. Just do the following:

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy HH:mm"

    dateLabel.text = formatter.string(from: sender.date)
}

This will convert the date picker's chosen date to a string in the format dd.MM.yyyy HH:mm in local time.

Never use the description method to convert any object to a user presented value.




回答2:


Just used the function in your code(swift 4.2).

public func convertDateFormatter(date: String) -> String {

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)

guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}

Thanks



来源:https://stackoverflow.com/questions/41577781/swift-3-changing-date-format

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