1
votes

I need to take the NSString Dec 4, 2012, 12:33 PM and convert it to separate out the month, day, and year, so that I can have 3 different strings of 12, 04, and 2012.

I figure that I should convert the NSString to NSDate and then reformat the date to change out NSString, but am running into issues.

I have:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        [dateFormatter setDateFormat:@"MMM dd, yyyy, hh:mm p"];
        NSDate *dateFromString = [[NSDate alloc] init];

        dateFromString = [dateFormatter dateFromString:substring];
        NSLog(@"Date%@", dateFromString);
        [dateFormatter release];

However, the date keeps coming back null.

3
can you add the substring assignment?chancyWu
@user717452: your substring should be null or it doesn't contain full date..TamilKing
The substring is Dec 4, 2012, 12:33 PMuser717452
Take a look at the Apple's Data Formatting Guide. It's quite helpful about setting up different formatting: developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…Neeku

3 Answers

3
votes

The problem is with your locale I think. You should try to print how your dateFormatter formats current date [NSDate new].

It works for me:

NSString* substring = @"Dec 12 2012 12:08 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setDateFormat:@"MMM d yyyy h:mm a"]; // not 'p' but 'a'
NSDate *dateFromString = [dateFormatter dateFromString:substring];
2
votes

Convert

[dateFormatter setDateFormat:@"MMM dd, yyyy, hh:mm p"];

to, Because MMM dd, yyyy, hh:mm p not a valid date formate

 [dateFormatter setDateFormat:@"MMM dd, yyyy, hh:mm a"];

And

NSDate *dateFromString = [dateFormatter dateFromString:substring];

To get string again

NSLog(@"%@",[dateFormatter stringFromDate:dateFromString]);

for me NSLog is Dec 04, 2012, 12:33 PM

1
votes
#import "NSString+Date.h"

@implementation NSString (Date)

+ (NSDate*)stringDateFromString:(NSString*)string;

{
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}

+(NSString*)StringFromDate :(NSDate*)date;

{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
return stringDate;
 }

` @end