如何在Swift iOS中将字符串日期转换为字符串? [英] How to convert string to date to string in Swift iOS?

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

问题描述

我很快学会了将日期String转换为NSDate转换为string的过程.我正在以这种格式获取日期字符串:"2015年10月22日星期四07:45:17 +0000".我需要以MM-dd-yyyy格式显示日期.我尝试了以下代码,但返回"null".

Am learning swift and am struck in converting the date String to NSDate to string. Am getting the date string in this format "Thu, 22 Oct 2015 07:45:17 +0000". I need to show the date in the MM-dd-yyyy format. I tried the following code but, it returns "null".

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateObj = dateFormatter.dateFromString(dateString!)
print("Dateobj: \(dateObj)")

任何人都可以帮忙解决问题吗?期待帮助.提前致谢.

Can anyone please help where am going wrong? Looking forward the help. Thanks in advance.

推荐答案

首先,您需要使用其格式将字符串转换为NSDate.然后,将dateFormatter更改为简单格式,然后将其转换回字符串.

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

快捷键3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

打印结果为:Dateobj: 10-22-2015

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

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