我的字典中有一个字符串"hoursOfOperation"从一个有如下格式NSString的服务中获取:"09:00 AM - 05:30 PM"每个对象的时间变化(可以是上午8点到下午4点等)
我如何重新格式化它,使它变成&;上午9点到下午5:30;在objective - c中?
我能够通过使用stringbyreplacingoccurrencesofstring来改变am/pm,但我不确定如何重新格式化时间。现在看起来是"上午9点到下午5点30分">
总之,要格式化日期/时间,你需要一个NSDateFormatter。在您的例子中,有几个步骤:
- 划分"09:00 AM - 05:30 PM"转换成两个不同的NSString变量
- 对于每个NSString变量,您需要将其转换为NSDate并使用NSDateFormatter设置日期格式,然后将其转换回所需的日期字符串
- 将刚才格式化的两个NSString添加到数组中
- 将这些对象连接在一起形成最终的时间字符串。
代码示例:
NSString *yourString = @"09:00 AM - 05:30 PM";
NSArray *timeComponents = [yourString componentsSeparatedByString:@" - "];
NSMutableArray *formattedTimeComponents = [NSMutableArray array];
for (NSString *timeComponent in timeComponents) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *time = [dateFormatter dateFromString:timeComponent];
[dateFormatter setDateFormat:@"h:mm a"];
dateFormatter.AMSymbol = @"a.m.";
dateFormatter.PMSymbol = @"p.m.";
NSString *formattedTime = [dateFormatter stringFromDate:time];
[formattedTimeComponents addObject:formattedTime];
}
NSString *formattedHoursOfOperationString = [formattedTimeComponents componentsJoinedByString:@"-"];
您应该使用NSDateIntervalFormatter
来生成正确定位并正确处理时区的结果。
你真的,真的,真的不应该自己手动修改AM/PM格式,因为那不会正确地本地化。
要做到这一点,你需要计算正确的开始&从原始字符串中使用结束日期。
NSDateFormatter *parseFormatter = [[NSDateFormatter alloc] init];
// You should probably set the timeZone for the formatter
parseFormatter.dateStyle = NSDateFormatterNoStyle;
parseFormatter.timeStyle = NSDateFormatterShortStyle; // This might not be the correct style. You should test this with your actual data.
NSArray *times = [originalTimes componentsSeparatedByString:@" - "];
NSDate *startDate = [parseFormatter dateFromString:times[0]];
NSDate *endDate = [parseFormatter dateFromString:times[1]];
接下来,创建一个日期间隔格式化程序,它将为您正确地本地化范围。
NSDateIntervalFormatter *intervalFormatter = [[NSDateIntervalFormatter alloc] init];
formatter.dateStyle = NSDateIntervalFormatterNoStyle;
formatter.timeStyle = NSDateIntervalFormatterShortStyle;
// You may also want to set timeZone for time zone you want to be shown in
NSString *result = [formatter stringFromDate:startDate toDate:endDate];