Swift - 将字符串转换为返回正确日期前一天的日期
Swift - converting string to date returning one day prior to correct date
我正在尝试将日期字符串转换为 Swift 中的日期。我的日期字符串返回为:
“28/05/2020”
我有这个方法:
private func getDate(date: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
return dateFormatter.date(from: date)
}
但它正在返回:
Optional(2020-05-27 23:00:00 +0000)
为什么返回 27 号而不是 28 号?
试一试,它会起作用
func convertStringintoDate(dateStr:String, dateFormat format:String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier:"en_US_POSIX")
dateFormatter.timeZone = TimeZone.init(abbreviation: "GMT")
dateFormatter.dateFormat = format
if let startDate = dateFormatter.date(from: dateStr){
return startDate as Date
}
return Date() as Date
}
像这样调用这个函数:-
print(convertStringintoDate(dateStr: "28/05/2020", dateFormat: "dd/MM/yyyy"))
我正在尝试将日期字符串转换为 Swift 中的日期。我的日期字符串返回为:
“28/05/2020”
我有这个方法:
private func getDate(date: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
return dateFormatter.date(from: date)
}
但它正在返回:
Optional(2020-05-27 23:00:00 +0000)
为什么返回 27 号而不是 28 号?
试一试,它会起作用
func convertStringintoDate(dateStr:String, dateFormat format:String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier:"en_US_POSIX")
dateFormatter.timeZone = TimeZone.init(abbreviation: "GMT")
dateFormatter.dateFormat = format
if let startDate = dateFormatter.date(from: dateStr){
return startDate as Date
}
return Date() as Date
}
像这样调用这个函数:-
print(convertStringintoDate(dateStr: "28/05/2020", dateFormat: "dd/MM/yyyy"))