Search code examples
swiftnsdateformatter

Using DateFormatter to return iOS lock screen date style


There seem to be five date styles for the DateFormatter class: none, short, medium, long, and full. However, none of these seem to return the lock screen date style, which is as follows:

Tuesday, 6 June

Using DateFormatter's .long style returns the year as well:

Tuesday, 6 June 2017

Additionally, this lock screen date style will change with the current localization/regional settings.

Is there a way to return the date, à la iOS lock screen date style (along with localizational changes)?


Solution

  • You can get the localized format for any combination of date components:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE MMMM d")
    
    print(dateFormatter.string(from: date)) // Friday, 4 August
    

    In Spanish:

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "es")
    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE MMMM d")
    
    print(dateFormatter.string(from: date)) // viernes, 4 de agosto
    

    Note how the order of components has been automatically changed and correct separators inserted.