2

My property dob of Patient object is String and currently storing 12-Jan-2017 and I want to convert it to French locale such as 12-Janv.-2017.

Below are my steps:

Converting 12-Jan-2017 into 1954-09-07 04:00:00 UTC

let dateFormatter        = NSDateFormatter()  
dateFormatter.locale     = NSLocale.init(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd-MMM-yyyy" 
let date                 = dateFormatter.dateFromString("12-Jan-2017") // now date is 1954-09-07 04:00:00 UTC

Next I have to set the locale of dateFormatter to fr

dateFormatter.locale = NSLocale.init(localeIdentifier: "fr")
let frenchDate       = dateFormatter.stringFromDate(date!) // now it is 12-Janv.-2017 

I dont think it is the best way to do a conversion. Are there any other efficient way for it. Any comments are welcomed.

tonytran
  • 1,068
  • 2
  • 14
  • 24
  • That is exactly how it is done. What are you worried about? – Martin R Jan 12 '17 at 20:12
  • @MartinR: only thing I concern is that it takes me 2 steps: `1. converting Jan to 1` then `2. convert 1 into Janv.`. I thought there should be the way directly to convert `Jan` to `Janv` – tonytran Jan 12 '17 at 20:14

1 Answers1

5

(NS)DateFormatter has methods to convert a date to a string representation and vice versa. There is no (built-in) method to convert from one date format directly to another format without intermediate (NS)Date. So what you are doing is fine.

Some suggestions though:

  • Use optional binding instead of forced unwrapping to avoid a crash at runtime if the input string is not in a valid format.
  • Use DateFormatter.dateFormat(fromTemplate:...) to get the date format string appropriate for the chosen locale.

Then your code would be (in Swift 3):

let inputDate = "12-Jan-2017"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd-MMM-yyyy"

if let date = dateFormatter.date(from: inputDate) {
    dateFormatter.locale = Locale(identifier: "fr")
    dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "dd-MMM-yyyy", options: 0, locale: dateFormatter.locale)

    let frenchDate = dateFormatter.string(from: date)
    print(frenchDate) // 12 janv. 2017
} else {
    print("invalid input date")
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382