Format a date from a string

前端 未结 5 1884
盖世英雄少女心
盖世英雄少女心 2020-12-10 08:37

I\'m trying to format a date from a string into another format.

For example: 2012-05-29 23:55:52 into 29/05 *newline* 2010.

I just

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 09:05

    For those who prefer to use extension.

    extension String {
    func formattedDate(inputFormat: String, outputFormat: String) -> String {
        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = inputFormat
    
        if let date = inputFormatter.date(from: self) {
            let outputFormatter = DateFormatter()
            outputFormatter.dateFormat = outputFormat
            return outputFormatter.string(from: date)
        } else {
            return self  // If the string is not in the correct format, we return it without formatting
        }
    }
    

    Use:

    tfDate.text = strDate.formattedDate(inputFormat: "yyyy-MM-dd", outputFormat: "dd/MM/yyyy")
    

提交回复
热议问题