Swift 3 changing date format

空扰寡人 提交于 2019-12-05 19:35:53

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.

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

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