將字符串轉換爲日期我有日期字符串下面的代碼格式要在Date
改變,但我越來越nil
斯威夫特
let addedDate = "Tue, 25 May 2010 12:53:58 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "dd MM YYYY"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")
將字符串轉換爲日期我有日期字符串下面的代碼格式要在Date
改變,但我越來越nil
斯威夫特
let addedDate = "Tue, 25 May 2010 12:53:58 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "dd MM YYYY"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")
日期格式必須是對於您要轉換的字符串,而不是您想要的格式
所以
formatter.dateFormat = "dd MM YYYY"
應該
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
如果你想以這種格式顯示日期,你需要設置另一個格式化器 - 看看https://stackoverflow.com/a/42231620/285190 – Flexicoder
您還必須將語言環境設置爲英語。 – Sulthan
你有你的字符串(addedDateString)轉換爲日期? (addedDate),那麼你可以使用你想要的格式將它轉換爲一個String(dateString)。請注意:從String到Date的轉換失敗時,addedDate爲零。
import UIKit
let addedDateString = "Tue, 25 May 2010 12:53:58 +0000"
// Transform addedDateString to Date
let addedDateFormatter = DateFormatter()
addedDateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
if let addedDate = addedDateFormatter.date(from: addedDateString) {
// Converstion String to Date return a valid Date
print ("addedDate", addedDate)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM YYYY"
let dateString = dateFormatter.string(from: addedDate)
print("Date: ", dateString)
} else {
// addedDate == nil value when conversion String to Date failed
print ("addedDateString not valid")
}
您也可以製作一個功能。類似這樣的:
func transformStringDate(_ dateString: String,
fromDateFormat: String,
toDateFormat: String) -> String? {
let initalFormatter = DateFormatter()
initalFormatter.dateFormat = fromDateFormat
guard let initialDate = initalFormatter.date(from: dateString) else {
print ("Error in dateString or in fromDateFormat")
return nil
}
let resultFormatter = DateFormatter()
resultFormatter.dateFormat = toDateFormat
return resultFormatter.string(from: initialDate)
}
print (transformStringDate("Tue, 25 May 2010 12:53:58 +0000",
fromDateFormat: "E, d MMM yyyy HH:mm:ss Z",
toDateFormat: "dd MM YYYY") ?? "Error")
您是否注意到'dateFormat'與'addsDate'的格式根本不匹配? – vadian
如果我知道那件事,爲什麼我會在這裏問.. –