你可以做的是使Date
擴展爲你這個TimeZone
設置爲DateFormatter
成甲酸你的約會,所以使兩個擴展一個Date
,一個用於String
。
extension Date {
struct CustomDateFormatter {
static var currentTimeZone = TimeZone.current //Set default timeZone that you want
static func dateFormatter(withFormat format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.timeZone = CustomDateFormatter.currentTimeZone
formatter.dateFormat = format
return formatter
}
}
func toDateString(withFormat format: String) -> String {
return CustomDateFormatter.dateFormatter(withFormat: format).string(from: self)
}
}
extension String {
func toDate(withFormat format: String) -> Date? {
return Date.CustomDateFormatter.dateFormatter(withFormat: format).date(from: self)
}
}
現在,當以往任何時候都需要設置TimeZone
或要轉換Date
到String
,反之亦然使用這個擴展這樣的。
//Set timezone
Date.CustomDateFormatter.currentTimeZone = TimeZone(abbreviation: "GMT")!
//get date from String
let date = "31-05-2017 07:30:05".toDate(withFormat: "dd-MM-yyyy HH:mm:ss")
//get string from date with specific format
let dateString = Date().toDateString(withFormat: "dd-MM-yyyy HH:mm:ss")
這工作得很好!謝謝! – SquareBox
@SquareBox歡迎伴侶:) –