Optional Date is not working?

Optional Date is not right working on my code. This is my code.

extension String {
    func toDate(format: String = "yyyyMMddHHmmssSSS") -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: self)

apiOutput has these datas.

▿ apiOutput
  ▿ stockStartDate : Optional<String>
    - some : "20200722"
  ▿ stockEndDate : Optional<String>
    - some : "20200722"

I executed this code.

let stockStartDate = apiOutput.tmStockStartDate?.toDate(format: "yyyyMMdd")

Then, I want have a result is stockStartDate has optional-date value, but this result is nil.

スクリーンショット 2020-07-22 15.34.44

addition, i tried the variant print on LLDB-console, then the variant has a result i want.

(lldb) po stockStartDate
▿ Optional<Date>
  ▿ some : 2020-07-21 15:00:00 +0000
    - timeIntervalSinceReferenceDate : 617036400.0

I can't understand what's happend.

I'm sorry. My English is so bad. Please let me know if I say something that's unclear.

If the debugger shows the expected value, why do you think it's nil? I see the screenshot of the mouse-over debug view, but perhaps the bug is there, and not in optionals. Maybe you moused over before the value was set.

1 Like

Thank you for reply.

I think mouse-over debug view has bug, too. but variant-viewer is also result nil.

スクリーンショット 2020-07-22 16.19.56

Never trust the Swift debugger!
If you ever see debugger showing a value you don't expect, try adding print and recompiling your code to make sure debugger isn't lying to you.

1 Like

In addition to what others have said, you need to be very careful when using DateFormatter to parse fixed-format date strings that don’t include a time. I posted an in-depth explanation of this to DevForums.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Terms of Service

Privacy Policy

Cookie Policy