从字符串中取回日期

Getting back a date from a string

我正在处理日期,但我在从字符串中取回日期时遇到了问题,我在这里简化了我的问题:

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

输出为: “25-05-2015”(很好) "Dec 21, 2014, 12:00 AM" (???)

问题是 Y 是给 weekOfYear 的。你必须使用 "dd-MM-yyyy"。顺便说一句,别忘了 set your date formatter locale to "en_US_POSIX" .

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iOS as it does on OS X, and as it it does on other platforms).

您应该使用 yyyy 作为年份,而不是 YYYY(具有不同的含义)

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" (*)

(*) 是 22:00 因为我在 +0200 时区,所以这个结果实际上是 2015-05-25 00:00:00 在我的时区

您应该更改日期格式以使其正常工作,YYYY 不正确。

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)")