如何将字符串日期转换为NSDate?

时间:2016-03-19 07:34:44

标签: ios swift nsdate

我想将ViewBag转换为2016-03-09 00:00:00

我正在尝试下面的代码,但打印09/03/2016

nil

以上代码打印var date: [String] = ["2016-03-09 00:00:00", "2016-03-20 00:00:00"] for i in date { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd/MM/YYYY" let showDate = dateFormatter.dateFromString(i) print(showDate) }
请帮助我如何在swift中打印日期nil格式

3 个答案:

答案 0 :(得分:3)

我认为您的日期格式错误。将“dd / MM / YYYY”更改为“YYYY-MM-dd HH:mm:s”并尝试...

  

您的日期类似于“2016-03-09 00:00:00”..因此格式应为“YYYY-MM-dd HH:mm:s”

for i in date {
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:s"
  if let showDate = dateFormatter.dateFromString(i){
     print("Date with Time: \(showDate)")
     dateFormatter.dateFormat = "YYYY-MM-dd"
     let resultString         = dateFormatter.stringFromDate(showDate)
     print("final result: \(resultString)")  
  }
}  

结果: -

Date with Time: 2016-03-09 00:00:00 +0000
final result: 2016-03-09 
Date with Time: 2016-03-20 00:00:00 +0000
final result: 2016-03-20 

答案 1 :(得分:1)

您应该首先创建一个dateformatter来处理该类型。然后对您的格式进行排序,例如:

let date: [String] = ["2016-03-09 00:00:00", "2016-03-20 00:00:00"]

for i in date {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:s"
    let showDate:NSDate? = dateFormatter.dateFromString(i)

    dateFormatter.dateFormat = "dd/MM/YYYY"
    let date = dateFormatter.stringFromDate(showDate!)
    print(date)

}

答案 2 :(得分:1)

在@ElCaptain的答案中,我建议不要在每次传递循环中重新配置单个日期格式化程序,而是建议在循环外创建2:输入日期格式化程序,用于转换来自" YYYY-MM-dd HH :MM:S"日期字符串为NSDates,输出格式化程序用于从NSDates转换为" YYYY-MM-dd"格式。

let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "YYYY-MM-dd HH:mm:s"
let outputFormatter = NSDateFormatter()
ourputFormatter.dateFormat = "YYYY-MM-dd"

for i in date {
  if let showDate = inputFormatter.dateFromString(i) {
     print("Date with Time: \(showDate)")
     let resultString = outputFormatter.stringFromDate(showDate)
     print("final result: \(resultString)")  
  }
}