ios Swift 3 更改日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41577781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:02:39  来源:igfitidea点击:

Swift 3 changing date format

iosswiftdatedatepickernsdateformatter

提问by Jochen ?sterreicher

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

我想将 DD.MM.YYYY HH:mm:ss 中的日期作为字符串获取。

I use the following extension:

我使用以下扩展名:

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

and the following code when my datePicker changes:

以及当我的 datePicker 更改时的以下代码:

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

我究竟做错了什么?

回答by rmaddy

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:mmin local time.

这会将日期选择器选择的日期转换dd.MM.yyyy HH:mm为本地时间格式的字符串。

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

切勿使用该description方法将任何对象转换为用户呈现的值。

回答by Nil Rathod

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

刚刚在您的代码中使用了该函数(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

谢谢