将日期字符串转换为正确格式 [英] Convert date string into proper format

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

问题描述

我从服务器收到回复,并且我需要将日期字符串转换为日期:

I am getting a response from a server and there is a date string I need to convert into a date:


Thu Jun 29 07:15:25 +0000 2017

Thu Jun 29 07:15:25 +0000 2017

我正在尝试将字符串转换为人类可读的格式。任何人都可以建议如何将此字符串转换为日期?

I am trying to convert the string into a human readable format. Can anyone suggest how to convert this string into date?

推荐答案

您需要将日期字符串解析为 Date 使用 DateFormatter 的对象,然后使用另一个 Date 创建一个字符串 DateFormatter ,包含您要使用的输出格式。

You need to parse the date string into a Date object using a DateFormatter, then create a string from that Date using another DateFormatter with the output format you want to use.

let created_at = "Thu Jun 29 07:15:25 +0000 2017"
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss Z yyyy"
guard let date = df.date(from: created_at) else {return}
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = "EEE, MMM d"
let outputDate = outputFormatter.string(from: date)

如果您想知道日期格式是什么样的,请使用 NSDateFormatter.com ,它有一个交互式界面,您可以在其中使用不同的日期格式并拥有大多数通讯的示例n格式。

If you want to know what date formats look like, use NSDateFormatter.com, which has an interactive interface where you can play around with different date formats and have examples of most common formats as well.

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

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