swift - Convert a String to a Date and then to a String in a different format

余生颓废 提交于 2019-11-30 10:20:29

Updated for Swift 3.0

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)

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.

The Apple developer guides explain it like this.

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.

You will need two date formatters as others suggested. Additionally, one of your issues is that you are using .A instead of .S for the fractional seconds. (See the link to Unicode Date Format Specification as pointed out in @MartinR's comment)

.A is Milliseconds in day

.S is Fractional Second

The the following in a Playground:

let dateString = "2015-11-25 04:01:32.0"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"                 // Note: S is fractional second
let dateFromString = dateFormatter.dateFromString(dateString)      // "Nov 25, 2015, 4:31 AM" as NSDate

let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "MMM d, yyyy"

let stringFromDate = dateFormatter2.stringFromDate(dateFromString!) // "Nov 25, 2015" as String
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!