如何在Swift 3中将字符串转换为日期而无需时间? [英] How to convert string to date without time in Swift 3?

查看:105
本文介绍了如何在Swift 3中将字符串转换为日期而无需时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试将日期(如2017-02-11字符串)转换为日期,但结果却给了我类似2017-02-10 16:00:00 +0000的信息.我在下面使用以下代码.

I have try to convert the date like 2017-02-11 string to date but the result give me back something like this 2017-02-10 16:00:00 +0000 . I am using the following code below.

let localDate = dateFormatter.string(from: date) //2017-02-11

    let dateFormatter2 = DateFormatter()
    dateFormatter2.dateFormat = "yyyy-MM-dd"

    let selectedDate = dateFormatter2.date(from: localDate)
    print("Did Select \(selectedDate)") // 2017-02-10 16:00:00 +0000

推荐答案

let dateWithTime = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short

let date = dateFormatter.string(from: dateWithTime) // 2/10/17

这将正确设置其格式,但这仅用于显示目的.所有Date都有时间.

This will format it correctly, but this will be for display purposes only. All Dates have time.

这篇关于如何在Swift 3中将字符串转换为日期而无需时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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