0

So, I was looking another question over here, and cross upon this:

I have an extension for NSDate

extension NSDate {
    private class var formatter : NSDateFormatter {
        let nsDateFormatter = NSDateFormatter()
        nsDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
        nsDateFormatter.locale = NSLocale.currentLocale()
        return nsDateFormatter
    }
    //NSString to NSDate
    public convenience init(dateString:String) {
        let dateObj = NSDate.formatter.dateFromString(dateString)!
        self.init(timeInterval: 0, sinceDate: dateObj)
    }

    //NSDate to String
    public func getString() -> String {
       return NSDate.formatter.stringFromDate(self)
    }
}

This works just fine:

var date = NSDate()                       //"Feb 2, 2016, 12:36 PM"
var string = date.getString()             //"2016-02-02 12:36:11 -0500"

let copyDate = NSDate(dateString: string) //"Feb 2, 2016, 12:36 PM"
copyDate.getString()                      //"2016-02-02 12:36:11 -0500"

But if I use, for example:

"EEE, d MMM YYYY HH:mm:ss zzz" as the dateFormat:

var date = NSDate()                       //"Feb 2, 2016, 12:58 PM"
var string = date.getString()             //"Tue, 2 Feb 2016 12:58:48 GMT-5"

let copyDate = NSDate(dateString: string) //"Dec 22, 2015, 12:58 PM"
copyDate.getString()                      //"Tue, 22 Dec 2015 12:58:48 GMT-5"

Why is this happening?

It shouldn't be working equal to the previous case?

Why I have now several days and even a month of time disruption?

Hugo Alonso
  • 6,684
  • 2
  • 34
  • 65

1 Answers1

1

You are using capital Y for year instead of y.

Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.

Change the format to "EEE, d MMM yyyy HH:mm:ss zzz"

You can read more about ISO week date here: https://en.wikipedia.org/wiki/ISO_week_date

Joe
  • 56,979
  • 9
  • 128
  • 135
  • Yes, this did the trick. This happens only with years? – Hugo Alonso Feb 02 '16 at 18:15
  • No there are other formatting options in the date format link I provided. For example, `D` is day of the year instead of day of the month. – Joe Feb 02 '16 at 18:18
  • by the way, even if this is the correct way to do it. Why it fails? The NSDateFormatter is the same for both, it shouldn't be returning the same data? – Hugo Alonso Feb 02 '16 at 18:30
  • The format doesn't match what is expected. ISO week dates are a whole other beast that I'm not an expert in. But to see consistent results use the expected format: `"YYYY'W'wwe"`. – Joe Feb 02 '16 at 18:39