I have a string in my dictionary "hoursOfOperation" from a service that has an NSString in this format: "09:00 AM – 05:30 PM" and the hours change for each object (can be 8 am – 4 pm etc)
How can I re-format this so that it becomes "9 a.m.-5:30 p.m." in objective-C?
I was able to change the am/pm by just using stringByReplacingOccurencesOfString but I am not sure how to reformat the time. Right now it looks like "09:00 a.m. – 05:30 p.m."
2
Answers
In short, to format a date/time, you need a NSDateFormatter.
In your case, there are several steps:
Code sample:
You should use
NSDateIntervalFormatter
to produce a result that localizes correctly and properly handles time zones.You really, really, really shouldn’t be manually messing with AM/PM formats yourself because that won’t localize properly.
To do that, you’ll need to calculate the correct start & end dates to use from the original string.
Next, create a date interval formatter, which will properly localize the range for you.