Search code examples
swiftxcodensdatedateformatter

How do I make a day come first while using the dateStyle in Swift


I want to make the day come first instead of the month while using the dateStyle feature of DateFormatter(). I tried all possible ways I know but nothing seems to work. Here is my code.

        let dateFormatter = DateFormatter()           
        dateFormatter.dateFormat = "dd MMM yyyy"
        print(dateFormatter.string(from: beginDate))  //05 Jul 2020          
        dateFormatter.doesRelativeDateFormatting = true           
        dateFormatter.dateStyle = .medium            
        print(dateFormatter.string(from: beginDate)) //Jul 5, 2020

I want the last line to print "5 Jul, 2020". The dateStyle is important becuase without that the dateFormatter.doesRelativeDateFormatting will not work. There should be a simple way to do it. Please Help.


Solution

  • You don't actually need to change anything in your code. Just switch your Simulator's Region (Settings -> General -> Language & Region) to a place that uses the little endian (day, month, year) style (here's a list). A typical example is the UK.

    If you want to always show the day first, regardless of the user's region, you can set the locale of the date formatter to one of those countries listed above:

    dateFormatter.locale = Locale(identifier: "en-GB")
    

    But I don't recommend this. You should not disrespect the user's language and region and their preferred date format unless you have a really good reason.