How to convert 24 hr String time into 12 hr time S

2019-03-15 17:25发布

I have time in NSString like "15:15"

I want to covert this NSString time into 12 hr NSString(i.e "3:15 PM").

4条回答
祖国的老花朵
2楼-- · 2019-03-15 17:44

@python

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"hh:mm"];

Hope this helps!

查看更多
孤傲高冷的网名
3楼-- · 2019-03-15 17:47

Check out this SO question: NSDateFormatter dateFromString and iPhone in 24 Hour Format Confusion

You should be able to use to use NSDateFormatter to format the style of time you want, then read in the string to the formatter and pull it back out in your desired format.

查看更多
女痞
4楼-- · 2019-03-15 17:51
// Get your 24 hr time String format
NSString *timeString = [NSString stringWithFormat:@"%@",[[[arr valueForKey:@"data"] valueForKey:@"pickup_time"] objectAtIndex:indexPath.row]]; 

//Store your 24 hr time String format into string
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm:ss"];
        NSDate *time = [dateFormatter dateFromString:timeString];

// Convert time object into desired format
[dateFormatter setDateFormat:@"hh:mm.a"];
cell.lbl_BookingTm.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:time]];    //Get your string into 12 hr time String format 
查看更多
啃猪蹄的小仙女
5楼-- · 2019-03-15 18:07

Use NSDateFormatter to turn the string in a NSDate. Then use the dateformatter again to change the NSDate to a string.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH:mm";
NSDate *date = [dateFormatter dateFromString:@"15:15"];

dateFormatter.dateFormat = @"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];

Code might contain some errors, written without compiling or testing.

查看更多
登录 后发表回答