jenny sam
jenny sam

Reputation: 191

How to extract the date from Swift String as NSDate?

My date is "2017-05-04 13:46:36.0". How can I filter only the date from this?

I have used this function:

func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = dateFormat
  dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
  dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  let convertedDate = dateFormatter.dateFromString(dateString)
  return convertedDate
}

let date = "2017-05-04 13:46:36.0"

now I have tried tried to set:

lbl.text = String.toDate(dateString: date, dateFormat: "yyyy-MM-dd")

But it always returns nil and crashes the app? Why is this happening?

Upvotes: 1

Views: 4040

Answers (2)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16426

You have wrong Parameter passed

var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: Date? = dateFormatter1.date(from: dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"

Rule of Date formatter is you must set date format same like your string while you are getting date from string , if mismatch then you will get null

Swift 2

var dateString: String = "2017-05-04 13:46:36.0"
var dateFormatter1: NSDateFormatter = NSDateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
var yourDate: NSDate = dateFormatter1.dateFromString(dateString)
dateFormatter1.dateFormat = "yyyy-MM-dd"
print("\(dateFormatter1.stringFromDate(yourDate))")

Upvotes: 3

Puneet Sharma
Puneet Sharma

Reputation: 9484

let dateString = "2017-05-04 13:46:36.0"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.0"
let date = dateFormatter.date(from: dateString)!
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.string(from: date)

Upvotes: 0

Related Questions