我将字符串转换为日期,但输出错误的日期。我通过替换 / 将格式日期从 json (30/12/2019) 更改为 - 符号 (30-12-2019) 但是将字符串转换为日期后的值显示输出 23-12-2018 输出错误的日期 为什么日期从 30-12 更改-2019 是 23-12-2018 我该如何解决这个问题?
来自 json 的值
self.FormattPlandate = dictionary["PlanDate"]! as? String
print("FormattPlandate ==>\(String(describing: self.FormattPlandate))”).
*//输出 30/12/2019
用于选择器视图
self.FormattpPlandateCategories = [self.getFormattDateTimes(textdate: self.FormattPlandate!)]
*// 输出错误的日期 23-12-2018
func getFormattDateTimes(textdate: String)-> String{
// let nowDate = textdate
print("formatter now from Json ==> \(nowDate)")
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(abbreviation: "UTC+7")
// replace / symbol to - symbol
let newDate: String = nowDate.replacingOccurrences(of: "/", with: "-")
formatter.dateFormat = "dd-MM-YYYY"
print("formatter now from Json replace / symbol to - symbol ==> \(newDate)")
// parse string to date
formatter.dateFormat = "dd-MM-YYYY"
let yourDate:Date = formatter.date(from: newDate)!
print("formatter yourDate from Json Result ==> \(formatter.string(from: yourDate))") —> why date change from 30-08-2019 to be 23-12-2018
// set format for display
formatter.dateFormat = "MMMM, dd YYYY"
print("formatter showDate from json Result ==> \(formatter.string(from: yourDate))") —> output wrong date 23 Dec 2018
// Equal Value For use in pickerview
getpPlanDatePickerView.text = formatter.string(from: yourDate)
getpShipmentPickerView.text = formatter.string(from: yourDate)
FormattpPlandateCategories = [formatter.string(from: yourDate)]
FormattgetpPlandateDCPlanData = [formatter.string(from: yourDate)]
let text = newDate
return text.uppercased()
}
Output
formatter now from Json ==> 30/12/2019
formatter now from Json replace / symbol to - symbol ==> 30-12-2019
formatter yourDate from Json Result after parse string to date ==> 23-12-2018
formatter showDate from Json Result after parse string to date ==> December, 23 2018