您可以做的是扩展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")