11

This might be a silly question, but I can't seem to find the answer on here or in the documentation.

I want to convert an NSString such as @"9/22/2010 3:45 PM" to an NSDate.

I know to use NSDateFormatter, but the problems are

  1. The month could be one or two digits
  2. Likewise, the date could be one or two digits
  3. Hours could be one or two digits
  4. What do I do about AM/PM?
cdeszaq
  • 30,869
  • 25
  • 117
  • 173
Kevin
  • 215
  • 4
  • 14

3 Answers3

27
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];

there is no problem in 2 digit day or 2 digit month.

This must help you.

Ishu
  • 12,797
  • 5
  • 35
  • 51
  • I got from this 11/20/2010 2:00 PM to 2009-12-27 19:00:00 GMT. Which isn't the same, obviously. – Kevin Dec 02 '10 at 07:40
  • Yes I'm using that precisely. Here's my code: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/YYYY h:mm a"]; NSDate *date = [dateFormat dateFromString:dateString]; NSLog(dateString); NSLog("%@", date); – Kevin Dec 02 '10 at 07:56
  • Sorry, that's a @" in the last NSLog, but still. It's not working. Simply returns the wrong date. – Kevin Dec 02 '10 at 08:01
  • Ah, fixed by looking up Unicode date formats. That should be lowercase Ys. as in yyyy, not YYYY. – Kevin Dec 02 '10 at 08:14
  • Ok fine @"MM/dd/yyyy h:mm a" use this one except @"MM/dd/YYYY h:mm a" – Ishu Dec 02 '10 at 08:17
  • It works properly and when you print date objects on NSLog then you see 2009-09-22 00: some thing like that but when you convert this in you string back with same format you get same string. – Ishu Dec 02 '10 at 08:20
  • Ok fine you get before my comment. – Ishu Dec 02 '10 at 08:26
  • i also change in my solution.for further help for others. – Ishu Dec 02 '10 at 08:27
3

You can parse an NSString into an NSDate using the NSDateFormatter class. See the documentation for more info:

Instances of NSDateFormatter create string representations of NSDate (and NSCalendarDate) objects, and convert textual representations of dates and times into NSDate objects.

Cameron Spickert
  • 5,190
  • 1
  • 27
  • 34
2

I was having the same problem, not sure why NSDateFormatter isn't working for me (iOS5 - Xcode 4.3.2) but this worked out for me:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = @"05-06-2012";
NSDate *date;
NSError *error = nil; 
if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
    NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
}
[dateFormatter release];
hackaroto
  • 21
  • 1