-2

Possible Duplicate:
Converting a string to an NSDate


I have date in string and want to convert in NSDate. In string date is:

"21st June 2012"

How can I convert this in NSDate?

Please concentrate on day "21st" not "21" when you give answer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
kokabwaqas
  • 87
  • 7
  • 7
    "If you want to end the hunger forever, dont give a fish to hungry man, teach him fishing".. I think this is an English idiom, google for 'convert NSString to NSDate' and read related topics on Apple Docs. Get started [now](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html) – ilhnctn Jan 30 '13 at 09:57
  • **11.422** SO questions regarding NSDates so far,see http://stackoverflow.com/search?q=NSDates, and **4745** for Your topic! Still repeating the questions . – DD_ Jan 30 '13 at 10:05
  • I can't find the way to convert the given date formate "21st June 2012" to NSDate. – kokabwaqas Jan 31 '13 at 07:37
  • 1
    Possible duplicate of [Converting a string to an NSDate](https://stackoverflow.com/questions/2311421/converting-a-string-to-an-nsdate) – Cœur Jul 08 '18 at 15:35
  • No, it's not a duplicate. The page you linked does not address parsing a string that uses ordinals (`21st` is an ordinal). Parsing the ordinal is what makes this question hard to answer. – rob mayoff Jul 08 '18 at 16:31
  • @robmayoff Not that hard: `if string == "21st June 2012" { return NSDate(timeIntervalSince1970: 1_340_208_000) }`. (OK, I added a better answer) – Cœur Jul 09 '18 at 05:46

2 Answers2

2

You can use NSDateFormatter to change NSString to NSDate.

Cœur
  • 37,241
  • 25
  • 195
  • 267
arun.s
  • 1,528
  • 9
  • 12
0

There is a generic answer for this kind of questions available on Stack Overflow, it's to use NSDateFormatter in Objective-C / DateFormatter in Swift. And the format is following tr35-19 or newer according to Use Format Strings to Specify Custom Formats.

But to deal with your variation of a date format, here is the Swift answer for your specific requirements:

// Your example
let dateString = "21st June 2012"

// Sanitizing input for 2nd, 3rd, 4th
let normalizedDateString = dateString.replacingOccurrences(of: "nd", with: "st").replacingOccurrences(of: "rd", with: "st").replacingOccurrences(of: "th", with: "st")

// Converting string to date object
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "d'st' MMMM yyyy"
let date = formatter.date(from: normalizedDateString)

Same logic in Objective-C.

Cœur
  • 37,241
  • 25
  • 195
  • 267