-2

How can a date be extracted from a string containing a timestamp using Swift?

For example:

When given the following timeStamp in string format, what steps are necessary to extract the date and convert it to a string?

if the timeStamp = "3/5/2015 7:12:17 PM"

then desired result would be = "3/5/2015"

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Michael Voccola
  • 1,827
  • 6
  • 20
  • 46
  • http://stackoverflow.com/a/27369380/2303865 – Leo Dabus Mar 06 '15 at 02:13
  • 2
    There are several thousand questions exactly like this on stack overflow already. By asking another one you're saying that none of those were able to help you in any way whatsoever? – Fogmeister Mar 06 '15 at 02:17
  • @Fogmeister The selected answer was able to provide additional insight into manipulating the timestamp that I was unable to harvest via existing Q&A's on Stack Overflow. Additionally, much of the existing information is in Objective-C. – Michael Voccola Mar 06 '15 at 02:52

1 Answers1

1
let input = "3/5/2015 7:12:17 PM"
let output = "3/5/2015"

extension NSDate {
    var formatted: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "M/d/yyyy"
        return formatter.stringFromDate(self)
    }
}
extension String {
    var asNSDate:NSDate {
        let styler = NSDateFormatter()
        styler.dateFormat = "M/d/yyyy h:mm:ss a"
        return styler.dateFromString(self) ?? NSDate()
    }
}

println( input.asNSDate.formatted ) // "3/5/2015"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571