Getting back a date from a string

2019-01-12 12:57发布

im dealing with dates, and i'm having problems getting my date back from a string, i simplified my problem here:

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-YYYY"
formatter.stringFromDate(date)
formatter.dateFromString(formatter.stringFromDate(date))

And the output is: "25-05-2015" (Which is fine) "Dec 21, 2014, 12:00 AM" (???)

3条回答
倾城 Initia
2楼-- · 2019-01-12 13:05

The problem there is that Y is for weekOfYear. You have to use "dd-MM-yyyy"

查看更多
地球回转人心会变
3楼-- · 2019-01-12 13:10

You should change your dateFormat to make it work , YYYY is not correct.

import Foundation

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-YYYY"
var firstDate = formatter.stringFromDate(date)
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
var secondDate = formatter.dateFromString(formatter.stringFromDate(date))
println("\(firstDate)")
println("\(secondDate)")
查看更多
爷的心禁止访问
4楼-- · 2019-01-12 13:13

You should use yyyy for the year, not YYYY (which has a different meaning)

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"

let s = formatter.stringFromDate(date) // "25-05-2015"
let d = formatter.dateFromString(s)    // "2015-05-24 22:00:00 UTC" (*)

(*) it's 22:00 because I'm in the +0200 timezone, so this result is effectively 2015-05-25 00:00:00 in my timezone

查看更多
登录 后发表回答