我的字符串是这种格式03/02/2017
我想像Mar 2, 2017
我一直试图让这个格式化程序工作,但它一直给我零,我不认为我是以正确的格式设置它。
// convert saved date from string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm/dd/yyyy" //Your date format
let date = dateFormatter.date(from: '03/02/2017')
print("\(date) save date") // nil
historyEntry.date = date as NSDate?
答案 0 :(得分:2)
不在
dateFormatter.dateFormat = "mm/dd/yyyy"
它在
dateFormatter.dateFormat = "MM/dd/yyyy"
完整输出
let dateFormatter = DateFormatter()
// iinitiallly set the date format based on your date
dateFormatter.dateFormat = "MM/dd/yyyy" //Your date format
// convert the string to date , but date is not the proper format , so dont worry about this
let date = dateFormatter.date(from: "03/02/2017")
// again reassign what the output you need set the date format
dateFormatter.dateFormat = "MMM dd, yyyy" // if you need the same as Mar 2, 2017 then use "MMM d, yyyy"
// finally convert your date to string
let myStringafd = dateFormatter.string(from: date!)
print("\(myStringafd) save date")
<强>输出强>
答案 1 :(得分:0)
let dateString = "03/02/2017"
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy" // this dateformat should be your current string's date format
df.timeZone = TimeZone(identifier: "UTC-05:00") // if there is timezone you want to set
if let date = df.date(from: dateString) {
df.dateFormat = "MMM dd, yyyy" // This dateformat is that you want as result
let stringFromDate = df.string(from: date)
cell.lblDate.text = stringFromDate
}