0

I'm converting date fields from a XML file and these dates are stored in "yyyyMMddHHmmss" format. When I use date function of DateFormmater, I'm not getting the correct time. So for dateString "20150909093700", it returns "2015-09-09 13:37:00 UTC" instead of "2015-09-09 09:37:00". I'm doing this conversion before storing inside Core Data NSDate fields.

This is my code :

static func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}
KMC
  • 1,677
  • 3
  • 26
  • 55
  • 1
    You are adding a timezone `dateFormatter.timeZone = TimeZone(abbreviation: "EST")` the offset of this timezone is used when calculation the date. Just a the UTC timezone. – rckoenes Mar 22 '17 at 14:04
  • 1
    @rckoenes The OP's code is fine. They are just misunderstanding the output of looking at the `Date` value. This has been covered so many times here. – rmaddy Mar 22 '17 at 14:16
  • @rmaddy on second read, you might be right. – rckoenes Mar 22 '17 at 14:17

1 Answers1

0

@user30646 -- see if this makes sense. Using your exact function:

func stringToDate(DateString dateString: String) -> NSDate? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMddHHmmss"
    dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")

    if let date = dateFormatter.date(from: dateString) {
        return date as NSDate?
    }

    return nil

}

let dateString = "20150909093700"

let returnedDate = stringToDate(DateString: dateString)

print("Date without formatting or Time Zone: [", returnedDate ?? "return was nil", "]")

let dFormatter = DateFormatter()
dFormatter.timeZone = TimeZone(abbreviation: "EST")
dFormatter.dateStyle = .full
dFormatter.timeStyle = .full

print("Result with formatting and Time Zone: [", dFormatter.string(from: returnedDate as! Date), "]")

You are getting the "correct time" ... you just think you're not because you're looking at the wrong string representation of that date/time.

DonMag
  • 69,424
  • 5
  • 50
  • 86