0

I can't find solution. My date formatter always returns nil, tried different formats but the result is the same. String looks like "2019-11-01T10:09:51.290"

extension DateFormatter {
    class func appdate(from date: String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
        let generatedDate = dateFormatter.date(from: date)
        return generatedDate
    }
}

Also I see something strange with po debugger, looks like it can create date but appdate function no(always returns nil):

(lldb) po dateFormatter.date(from: date)
▿ Optional<Date>
  ▿ some : 2019-11-01 07:09:51 +0000
    - timeIntervalSinceReferenceDate : 594284991.29
ArisRS
  • 1,362
  • 2
  • 19
  • 41
  • What specifically is the problem? Your code looks fine. The output looks fine. In what way are "milliseconds not working"? – rmaddy Nov 08 '19 at 19:34
  • appdate function returns nil – ArisRS Nov 08 '19 at 19:36
  • Show us [reproducible example](https://stackoverflow.com/help/mcve) where `appDate` was `nil`. Just telling us it is `nil` isn’t enough. I ran `appdate` with the input string you provided, and it works fine, so the problem rests elsewhere. – Rob Nov 08 '19 at 19:39
  • You should set the formatter's locale to `en_US_POSIX` and you probably want to treat your date string in UTC so you should also set the formatter's timezone appropriately. – rmaddy Nov 08 '19 at 19:43
  • By the way, a few unrelated observations: 1. Date formatters are notoriously expensive to create. So you don’t want to create a new one every time you call this `appdate` method. 2. You really should set `locale` of your date formatter, e.g. `dateFormatter.locale = Locale(identifier: "en_US_POSIX")`, so this will work for users with non-Gregorian calendars. 3. What is the timezone of this string? Usually we use gmt/utc/zulu, but your formatter is going to use the user’s local timezone (which can get you into problems). Was that your intent? – Rob Nov 08 '19 at 19:43

0 Answers0