format string date using DateFormatter

276 views Asked by At

I'm making a function to format string date (like "2018-05-01 18:23:31") to string type of Japanese date format, which is "2018年5月1日". I made a function but when I run it throws me an error saying

Fatal error: Unexpectedly found nil while unwrapping an Optional value

when I print my input string date, it has a value, but while it's converting, I start getting an error. Can anyone tell me why I'm getting nill in this function?

func setTemplate (strDate: String) -> String {
    
    let dateFormatter = DateFormatter()

    dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
    
    print(strDate) // getting this value => "2018-05-01 18:23:31"

    let date = dateFormatter.date(from: strDate)! // getting an error in here
    
    let result = dateFormatter.string(from: date)
    
    return result
}

I guess I'm trying to get rid of time in the string and it somehow throws me an error, but not sure...

1

There are 1 answers

0
Leo Dabus On BEST ANSWER

You need to first parse your string then you can get a localized string from the resulting date:

let strDate = "2018-05-01 18:23:31"
func setTemplate (strDate: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = .init(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    guard let date = dateFormatter.date(from: strDate) else { return nil }
    let locale = Locale(identifier: "ja_JP")
    dateFormatter.locale = locale
    dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: locale)
    return dateFormatter.string(from: date)
}
setTemplate(strDate: strDate)  // "2018年5月1日"