Nico
Nico

Reputation: 6369

Why can I not format my NSDate with the specified time zone with NSDateFormatter?

I want to get a date that is represented in a String with a time zone GMT+1 and display it on screen with the local time zone GMT+10.

I have 2 methods, one is for create a date from a String (with GMT+1 timeZone), the other one is to format the date into a String (with localTimeZone GMT+10):

func dateFromString(dateString: String) -> NSDate? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+1")
    dateFormatter.dateFormat = "M/d/yyyy hh:mma"

    return dateFormatter.dateFromString(dateString)
}

func stringFromDate(date: NSDate) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeZone = NSTimeZone.localTimeZone()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    return dateFormatter.stringFromDate(date)
}

In the playground, when I do this:

let date = dateFromString("4/8/2015 1:29am")!
println(date)
println(stringFromDate(date))

I get the following output on the right side:

"Apr 8, 2015, 1:29 AM"
"2015-04-07 15:29:00 +0000"
"1:29 AM"

I don't understand why I don't get what I am expecting and looking for:

"Apr 8, 2015, 1:29 AM"
"2015-04-08 10:29:00 +0000"
"10:29 AM"

What's wrong?

Upvotes: 0

Views: 338

Answers (2)

Alex Curylo
Alex Curylo

Reputation: 4770

Input formatters need the time zone in their string. Like so:

func dateFromString(dateString: String) -> NSDate? {
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = "M/d/yyyy hh:mma z"

  return dateFormatter.dateFromString(dateString)
}

let date = dateFromString("4/8/2015 1:29am GMT+01")!

Also note that NSTimeZone names have a two digit offset. Compare in the playground

var oops = NSTimeZone(abbreviation: "GMT+1")
var righteous = NSTimeZone(abbreviation: "GMT+01")

The first is nil, the second is not.

Upvotes: 2

Dare
Dare

Reputation: 2587

I wouldn't trust the formatting of a time stamp that the debugger prints. In my experience dates are always in UTC regardless of the time zone you set according to the log. Try adding the date as a string to a label on the project and see if it's right.

The reasoning behind this as far as I know is that when you print to the log, all it's doing is calling -description. In the case of NSDate this will return in UTC by definition.

Upvotes: 0

Related Questions