-7

I want to convert December 20, 2016 to 12/20/16.

December 20 is in String format. Not too sure if I can use NSDateFormatter for this. I do not what MM/DD/YYYY to something like YYYY:DD:MM. I want to convert a String December 20, 2016, and get it to 12/20/16.

3

1 Answer 1

0

Yes you can use DateFormatter (without NS in Swift 3, the same applies for Date not NSDate). To properly parse your date string you need to use the date format "MMMM dd, yyyy" and set the date formatter locale to "en_US_POSIX"

let string = "December 20, 2016"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy"

if let date = formatter.date(from: dateString) {
    print(date)  // "2016-12-20 02:00:00 +0000\n"
    formatter.dateStyle = .short
    let stringFromDate = formatter.string(from: date)   // "12/20/16"
}
Sign up to request clarification or add additional context in comments.

9 Comments

The question asks how to convert the first string into the second string. This is only half of the answer. And there must be many duplicates for this question.
The question is how to convert the date string (without time) to date.
That's what the title says but then the question shows two different date strings.
String date to NSDate? And the date format is totally different. I am pretty sure his goal is to get a date not a string
Exactly, two different date string formats. The question implies a conversion from one string to another string which is different from the question's title. Regardless, do we really need yet another date conversion question? Please vote to close such dupes instead of posting yet another answer that has been posted many, many, many times before. :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.