尝试将字符串重新格式化为特定的日期格式

时间:2017-03-03 04:29:40

标签: ios swift3 nsdate nsdateformatter

我的字符串是这种格式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?

2 个答案:

答案 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") 

<强>输出

enter image description here

答案 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
        }