1

I have a NSString like Mon Feb 06 20:02:17 +0000 2012. I want to write it in a shorter way, maybe like: DD-MM-YY, HH:MM. I have think that maybe I can convert it to NSDate and again to a shorter NSString, but I don't know how to convert this strange date format to NSDate.

If you need more information, ask me. Thanks!

Garoal
  • 2,364
  • 2
  • 19
  • 31
  • Check it out: [parsing date formats in cocoa](http://stackoverflow.com/questions/399527/parsing-unsupported-date-formats-in-via-cocoas-nsdate) – Matt Feb 06 '12 at 20:45

3 Answers3

3

There are similar question and answers in StackOverflow and a tutorial that may help you:

Tutorial: http://iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html

Similar questions:

EDIT

NSString *dateStr = @"20081122"; 

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  

// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sierra Alpha
  • 3,707
  • 4
  • 23
  • 36
3

You need to use an NSDateFormatter to tell NSDate the format the original date is in and the format you want it in, then you can convert between the two like this:

NSString *oldDate = @"Mon Feb 06 20:02:17 +0000 2012";
NSString *oldFormat = @"EEE MMM dd HH:mm:ss ZZ yyyy";

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:oldFormat];

NSDate *date = [dateFormatter dateFromString:sourceString];

NSString *newFormat = @"dd-MM-yy, HH:mm";

[dateFormatter setDateFormat:newFormat];
NSString *newDate = [dateFormatter stringFromDate:date];
Matt Garrod
  • 863
  • 6
  • 13
1

Try with NSDateFormatter.

You can convert to NSDate using one of its method:

- (NSDate *)dateFromString:(NSString *)string

And then convert that to whatever you want using NSDateFormatter.

Edit: Actually NSDate has a class method so you may check that as well:

+ (id)dateWithString:(NSString *)aString
nagan
  • 119
  • 3