NSDateFormatter的日期为nil,格式为'MMM dd,yyyy HH:mm a'

时间:2015-10-28 07:38:16

标签: ios swift2 nsdateformatter

我有let time = "Jun 08, 2015 11:27 PM",使用以下代码将其转换为NSDate

    let formatter = NSDateFormatter()
    formatter.dateStyle = .MediumStyle
    formatter.timeStyle = .ShortStyle
    let date = formatter.dateFromString(time)

获得date as nil,即使我尝试使用自定义格式化程序

    //MMM dd, yyyy HH:mm a
    //formatter.dateFromString("MMM dd, yyyy HH:mm a")

还没有工作,有什么遗失?

3 个答案:

答案 0 :(得分:1)

let time = "Jun 08, 2015 11:27 PM"

    let formatter = NSDateFormatter()

    formatter.dateFormat = "MMM dd, yyyy HH:mm a"

    let date = formatter.dateFromString(time)

    formatter.dateStyle = .MediumStyle
    formatter.timeStyle = .ShortStyle

     let newString = formatter.stringFromDate(date!)

     NSLog("the newString %@", newString)

      let newDate = formatter.dateFromString(newString)

     NSLog("the date %@", newDate!)

输出

newString 2015年6月8日,下午12:27

日期 2015-06-08 06:57:00 +0000

enter image description here

答案 1 :(得分:1)

我在Plyground中测试了以下内容并且它可以正常工作。

                            let time = "Jun 08, 2015 11:27 PM"

                            let formatter = NSDateFormatter()
                            formatter.dateFormat = "MMM dd, yyyy hh:mm a"
                            let date = formatter.dateFromString(time)

答案 2 :(得分:1)

请尝试以下代码:

func dateformat() 
{
    let time = "Jun 08, 2015 11:27 PM"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM dd, yyyy HH:mm a"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC");
    let date = dateFormatter.dateFromString(time)
    println(NSDate.date())
}