Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSString of a date to an NSDate

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?
like image 950
Kevin Avatar asked Dec 02 '10 06:12

Kevin


3 Answers

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.

like image 146
Ishu Avatar answered Nov 12 '22 21:11

Ishu


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.

like image 35
Cameron Spickert Avatar answered Nov 12 '22 21:11

Cameron Spickert


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];
like image 2
hackaroto Avatar answered Nov 12 '22 20:11

hackaroto