Search code examples
iosobjective-cnsdateformatter

How do I change NSTime format from hh:mm:ss to hh:mm a?


I want to change the time format from string, I am having the values in hh:mm:ss in 24 hr format and I want to make it hh:mm:a in 12 hr format.

I have tried -

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"hh:mm:ss"];

    NSDate *date123 = [format dateFromString:temp123];
    [format setDateFormat:@"hh:mm a"];
    NSString* newDateString = [format stringFromDate:date123];

please help me.


Solution

  • if your temp123 in 24 hour format, then use HH instead of hh

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"HH:mm:ss"];
    
    NSDate *date123 = [format dateFromString:temp123];
    [format setDateFormat:@"hh:mm a"];
    [format setAMSymbol:@"am"];
    [format setPMSymbol:@"pm"];
    NSString* newDateString = [format stringFromDate:date123];