0

My original date format is : 2014-03-14T10:35:24.537

So I first separate the time and date with componentsSeparatedByString, then I save the second half (the time part) to NSString time, while eliminating the microseconds. to the format 10:35. I'm trying to get it to add PM/AM but setDateFormat:@"hh:mm a" is not doing it. What am I doing wrong?

NSArray *components = [datestr componentsSeparatedByString:@"T"];
NSString *time = components[1];
time = [time substringWithRange:NSMakeRange(0, 5)];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSDate *timeFromString = [formatter dateFromString:time];
NSLog(@"%@", timeFromString);

When I log timeFromString, I get a null.

EDIT: I changed the formatter above to [formatter setDateFormat:@"hh:mm"]; and now the timeFromString logs as: 2000-01-01 18:35:00 +0000 when data coming in is 2014-03-14T10:35:28.42

user3178926
  • 339
  • 1
  • 5
  • 15
  • 2
    To convert the string to an `NSDate`, you need a format that matches the string you have. Then use a second format to get the new string that you want. – rmaddy Mar 14 '14 at 19:08
  • The output you are getting is correct. – rmaddy Mar 14 '14 at 19:11
  • This seems to be a duplicate of http://stackoverflow.com/questions/16254575/how-do-i-get-iso-8601-date-in-ios – David Berry Mar 14 '14 at 19:22

2 Answers2

1

A date formatter is used to convert dates to or from a string. A single date formatter cannot be used to convert between two different date formats. (At least, not without mutating the date formatter between operations.)

Use one formatter to convert the original string to a date. That formatter should not include AM/PM, since your original string doesn't.

Use a second formatter to convert the date to a new string. That formatter should include AM/PM, if you desire one.

Steven Fisher
  • 44,462
  • 20
  • 138
  • 192
1

Here 's how you should parse and convert the date:

//the date string
NSString *datestr = @"2014-03-14T10:35:24.537";

//strip the date
NSArray *components = [datestr componentsSeparatedByString:@"T"];
NSString *time = components[1];
time = [time substringWithRange:NSMakeRange(0, 5)];

//parse string to a date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSDate *timeFromString = [formatter dateFromString:time];

//Desired format
NSDateFormatter *timeformat = [[NSDateFormatter alloc] init];
[timeformat setDateFormat:@"hh:mm aa"];
NSString *finalString = [timeformat stringFromDate:timeFromString];

NSLog(@"final = %@",finalString);

OUTPUT:

final = 10:35 AM

meda
  • 45,103
  • 14
  • 92
  • 122