7

I have a quick question. According to apple official documentation https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/#//apple_ref/occ/instm/NSDateFormatter/dateFromString:

NSDateFormatter.dateFromString(String) would return

A date representation of string interpreted using the receiver’s current settings. If dateFromString: can not parse the string, returns nil.

Then I when I give it an empty string "", should it return nil? When I do this in the playground

let date = ""
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
print(dateFormatter.dateFromString(date))

It gave me

"Optional(1999-12-31 15:00:00 +0000)\n"

Is this happen to be a normal behaviour? Or am I doing something wrong?

Thank you

2
  • 2
    I agree that's a little strange, but the result makes sense given that your timezone is probably GMT+9. If your date format was yyyy-MM-dd, you would have gotten nil.
    – Rob
    Commented Jun 27, 2016 at 9:00
  • You are right, when I change it to "yyyy-MM-dd", NSDateFormatter gave me nil. I also think that it is very weird that it response differently when given different date format, which should just be how it parse the string
    – moka2258
    Commented Jun 27, 2016 at 9:19

2 Answers 2

2

If dateFromString: can not parse the string, returns nil

The simple answer is, the dateFromString does manage to parse an empty string. If you try and put wrong data in the string, say "0" then you will get nil.

Why is it happening? I assume that it is just they way the class is written, since the date formatter does skip missing data and try to complete it. There is probably not a case for "all is missing".

3
  • An empty input string is accepted for the date format "yyyyMMdd" and for "yyyyMM", but not for the date format "yyyy". There are other cases where missing data is not just "completed". For example the "yyyyMMddHHmm" format does not accept the input "2015" or "20150101". – So this does not fully explain it.
    – Martin R
    Commented Jun 27, 2016 at 9:24
  • Yes. I think that's what I said, try to complete the missing input. If it doesn't manage it returns nil.
    – Idan
    Commented Jun 27, 2016 at 9:41
  • In my opinion passing an empty string to DateFormatter should not return an unexpected random date; filed as Feedback FB14744080, hopefully to at least have a note added to the documentation if this behavior is by design.
    – cdf1982
    Commented yesterday
1

Exactly. If it's not possible to parse the string it will return nil but if you use an empty string it will return that date by default.

Change the "" for " " or anything to fill it if it's nil what you want to obtain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.