DateFormatter date from string returns nil

后端 未结 1 688
天涯浪人
天涯浪人 2021-01-04 13:55

For some reason some devices fail to convert a string to a date.

This is my date converting code:

func dateFromString(string: String) -> Date? {
          


        
相关标签:
1条回答
  • 2021-01-04 14:58

    If you’re showing your date to the user, don’t set fixed date format string. If you are using fixed-format dates, fix your locale first.

    For more details, see Technical Q&A QA1480 titled “NSDateFormatter and Internet Dates”. Below are relevant excerpts (formatting mine):

    Q: I'm using NSDateFormatter to parse an Internet-style date, but this fails for some users in some regions. I've set a specific date format string; shouldn't that force NSDateFormatter to work independently of the user's region settings?

    A: No. While setting a date format string will appear to work for most users, it's not the right solution to this problem. There are many places where format strings behave in unexpected ways. (…)

    If you're working with user-visible dates, you should avoid setting a fixed date format string because it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should limit yourself to setting date and time styles (via NSDateFormatter.dateStyle and NSDateFormatter.timeStyle) or generate your date format string from a template (using NSDateFormatter.setLocalizedDateFormatFromTemplate(String)).

    On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.

    0 讨论(0)
提交回复
热议问题