从 Swift 中的日期字符串转换日期

Converting date from date string in Swift

我有一个 2 January 2020 字符串格式的日期,我想将其转换为 2nd Jan, 2020

我试过以下代码但没有用:

static func formatDateFromDateTimeString(dateString: String, inputFormat: String = "yyyy-MM-dd'T'HH:mm:ss", outPutFormat:String = "dd MMM yyyy | hh:mm a" )->String {
    let inputDateFormatter = DateFormatter()
    inputDateFormatter.dateFormat = inputFormat
    let date = inputDateFormatter.date(from: dateString)
    let outputDateFormatter = DateFormatter()
    outputDateFormatter.dateFormat = outPutFormat
    if let safeDate = date {
        return outputDateFormatter.string(from: safeDate)
    }
    return ""
}

formatDateFromDateTimeString(dateString: "2 January 2020")

DateFormatter 不支持 序数 日期格式 1st, 2nd 例如你必须自己做

static func formatDateFromDateTimeString(dateString: String, inputFormat: String = "yyyy-MM-dd'T'HH:mm:ss") -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = inputFormat
    guard let date = dateFormatter.date(from: dateString) else { return nil }
    let day = Calendar.current.component(.day, from: date)
    dateFormatter.dateFormat = "MMM, yyyy"
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .ordinal
    guard let dayString = numberFormatter.string(from: day as NSNumber) else { return nil }
    return dayString + " " + dateFormatter.string(from: date)
}

formatDateFromDateTimeString(dateString: "2 January 2020", inputFormat: "dd MMMM yyyy") 

如果您需要这种特定的日期格式,outPutFormat 参数就没有意义。