Search code examples
iosxcodeswift3nsdateformatter

Date conversion is always nil in iPhone 24hr date format


i trying to convert string to Date which is properly working in 12hr date format. when i switch the device date format to 24, its always returning nil. Please check the below code

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mm a"
    let date = formatter.date(from: "6:00 am")

Solution

  • According to Technical Q&A QA1480:

    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.

    So, to prevent date from being interpreted using device's regional settings you need to set locale property of your DateFormatter

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "hh:mm a"
    let date = formatter.date(from: "6:00 am")
    

    Note: it's important you set locale before you set dateFormat