Swift - customizable local date formatting

Using swift I would like my custom dateFormatter.dateFormat to be MMM-d or d-MMM depending on the user's location. It seems straightforward enough if I used the default short.medium.etc style, but for design and layout reasons I need this custom format.

Any help?

+3


source to share


3 answers


You can read the current device language and set the format accordingly.

var dateFormat: String
switch NSLocale.currentLocale().localeIdentifier {
    case "en_US": dateFormat = "MMM d"
    ...
    default: dateFormat = "d MMM"
}

      

Also see NSDateFormatter.dateFormatFromTemplate

:



NSDateFormatter.dateFormatFromTemplate("MMM dd", options: 0, locale: NSLocale.currentLocale())

      

Which returns the format and order applicable for a given language, consisting of the elements you specify (month and day in this case), but not always "MMM d" or "d MMM" as you choose. You can run this to see the lines it actually generates for each locale:

let formatter: DateFormatter = DateFormatter()
for id in NSLocale.availableLocaleIdentifiers {
  let locale = NSLocale(localeIdentifier: id)
  let format = DateFormatter.dateFormat(fromTemplate: "MMM dd", options: 0, locale: locale as Locale) ?? "n/a"
  formatter.dateFormat = format
  formatter.locale = locale as Locale!
  let fd = formatter.string(from: NSDate() as Date)
  print("\(id)\t\(format)\t\(fd)")
}

      

+4


source


This is an old question, but I found it by doing some hard research. It was about time and Swift 3 came out. So I converted @ sagits answer to Swift 3 in case anyone needs it:



let myDate = "2017-08-19 13:52:58"

static func getFormatedDateTime(sqlDate: String?) -> String {

    if (sqlDate == nil || sqlDate == "") {
        return ""
    }

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss"
    let date = dateFormatter.date(from: sqlDate!)

    let localFormatter = DateFormatter.dateFormat(fromTemplate: "yyyy/MM/dd HH-mm", options: 0, locale: NSLocale.current)

    dateFormatter.dateFormat = localFormatter


    let outputDate = dateFormatter.string(from: date!)

    return outputDate
}

//Call the function out
getFormatedDateTime(sqlDate: myDate)

      

+1


source


The above answer when using sql datetime from server:

static func getFormatedDateTime(var sqlDate : String?) -> String {

    if (sqlDate == nil || sqlDate == "") {
        return "";
    }

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss"
    var date = dateFormatter.dateFromString(sqlDate!) as NSDate!

    let localFormatter = NSDateFormatter.dateFormatFromTemplate("yyyy/MM/dd HH-mm", options: 0, locale: NSLocale.currentLocale())

    dateFormatter.dateFormat = localFormatter

    let outputDate = dateFormatter.stringFromDate(date)

    return outputDate
}

      

0


source







All Articles