swift-将字符串转换为日期,然后转换为其他格式的字符串 [英] swift - Convert a String to a Date and then to a String in a different format

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

问题描述

假设我有一个简单的String,它是从一个字符串数组中提取的(代表日期)-

Suppose I have a simple String, extracted from an array of strings (representing dates) -

var myDateString = "2015-11-25 04:31:32.0"

现在,我想将其转换为类似于 2015年11月25日的字符串.

Now, I want to convert it to a string that looks like Nov 25, 2015.

为此,我认为我需要-

  • 使用NSDateFormatter从字符串获取NSDate日期对象
  • 通过使用某些功能(我一直找不到)从该NSDate对象中获取一个字符串

我曾在Playground中尝试过此方法,但无法解决这样一个简单的问题.

I've been trying this in Playground, but have been unable to solve such a simple problem.

这是我尝试过的-

Line 1| var dateFormatter = NSDateFormatter()
Line 2| dateFormatter.locale = NSLocale.currentLocale()
Line 3| dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss.A"
Line 4| let somedate = dateFormatter.dateFromString(str)
Line 5| let somedateString = dateFormatter.stringFromDate(somedate!)

在Xcode的侧边栏中,第4行打印"Nov 25, 2015, 12:00 AM",但是当我尝试从somedate打印字符串时,得到"2015-11-25 00:00:00.0".

In the sidebar of Xcode, line 4 prints "Nov 25, 2015, 12:00 AM", but when I try to print a string from somedate, I get "2015-11-25 00:00:00.0".

我在任何地方都找不到NSDates的正确解释.

I haven't found a single proper explanation of NSDates anywhere.

在Java中,使用日期的parse()format()函数非常容易.

This was so much easier in Java with parse() and format() functions for Dates.

推荐答案

已针对Swift 3.0更新

Updated for Swift 3.0

您需要两个日期格式化程序-一个用于理解您的输入字符串并将其转换为NSDate的日期格式化程序,以及一个用于创建输出字符串的另一个格式化程序

You need two date formatters - one to make sense of your input string and convert to a NSDate, and a different formatter to create the output string

    let myDateString = "2016-01-01 04:31:32.0"

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.A"
    let myDate = dateFormatter.date(from: myDateString)!

    dateFormatter.dateFormat = "MMM dd, YYYY"
    let somedateString = dateFormatter.string(from: myDate)

我已经更新了此答案,将日期格式从YYYY更改为yyyy.在大多数情况下,两者之间没有区别,但是YYYY可能会将一年的前几天视为上一年的最后一个完整周的一部分.

I have updated this answer to change the date formatter from YYYY to yyyy. In most cases, there will be no difference between the two, but YYYY may treat the first few days of the year as being part of the last complete week of the previous year.

Apple开发人员指南对此进行了解释.

The Apple developer guides explain it like this.

一个常见的错误是使用YYYY. yyyy指定日历年,而YYYY指定ISO年-周日历中使用的年份(年中的一周").在大多数情况下,yyyy和YYYY产生相同的数字,但是它们可能不同.通常,您应该使用日历年.

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

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

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