Getting back a date from a string

前端 未结 3 1521
梦如初夏
梦如初夏 2020-12-02 03:00

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 = NSDateF         


        
相关标签:
3条回答
  • 2020-12-02 03:46

    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)")
    
    0 讨论(0)
  • 2020-12-02 03:50

    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

    0 讨论(0)
  • 2020-12-02 03:51

    The problem there is that Y is for weekOfYear. You have to use "dd-MM-yyyy". Btw don't forget to 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).

    0 讨论(0)
提交回复
热议问题