Swift 3更改日期格式 [英] Swift 3 changing date format

查看:102
本文介绍了Swift 3更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以字符串形式在DD.MM.YYYY HH:mm:ss中获取我的日期。

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

我使用以下扩展名:

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

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

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

我是什么

推荐答案

您的代码完全错误。只需执行以下操作:

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

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

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.

这篇关于Swift 3更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆