iParesh
iParesh

Reputation: 2368

How can I convert string date to NSDate?

I want to convert 2016-03-09 00:00:00 to 09/03/2016

I am try below code but print nil value

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)
}

above code print nil
pls help me how to print date dd/MM/YYYY format in swift

Upvotes: 2

Views: 1815

Answers (3)

Duncan C
Duncan C

Reputation: 131408

Rather than reconfiguring a single date formatter on each pass through the loop in @ElCaptain's answer I would suggest creating 2 outside the loop: an input date formatter for converting from "YYYY-MM-dd HH:mm:s" date strings to NSDates, and an output formatter for converting from NSDates to "YYYY-MM-dd" format.

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)")  
  }
}  

Upvotes: 1

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

I think your date format is wrong. change "dd/MM/YYYY" with "YYYY-MM-dd HH:mm:s" and try ...

You have a date like "2016-03-09 00:00:00" .. so format should be "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)")  
  }
}  

Result:-

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 

Upvotes: 3

ridvankucuk
ridvankucuk

Reputation: 2407

You should first create a dateformatter to handle the type. Then sort your format such as:

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)

}

Upvotes: 1

Related Questions