I'm running into an issue when it comes to taking two NSDate
s and displaying a localized string for the range.
For example, say my dates are on July 7 and July 9. I would need the following localized strings:
Obviously using NSString stringWithFormat:
isn't going to work here. For the sake of simplicity, let's not even get into the case where your range is two separate months. I know how to get a formatted string for each date but it's formatting it in a range that is getting me.
Is there way of using an NSDateFormatter
to get this? The more I look around, the more I think I'm going to need to have a switch for each locale.
EDIT: To clarify, I only need the date range for the user's locale. I don't need all of them at the same time.
After further research it looks like in iOS 8.0+ you can use NSDateIntervalFormatter
to do this. That doesn't help me now but it's comforting to know it's on the way.
To elaborate on Adam's answer with some sample code:
let formatter = NSDateIntervalFormatter()
formatter.dateStyle = NSDateIntervalFormatterStyle.ShortStyle
formatter.timeStyle = NSDateIntervalFormatterStyle.NoStyle
let dateRangeStr = formatter.stringFromDate(startDate, toDate: endDate)
If you want to drop the year information you need to explicitly set the dateTemplate argument in NSDateIntervalFormatter.
So only with this solution you will get the result July 7-9 without date.
Objective-C
NSDate *startDate = [NSDate new];
NSDate *endDate = [[NSDate new] dateByAddingTimeInterval:10000];
NSDateIntervalFormatter *df = [[NSDateIntervalFormatter alloc] init];
df.dateTemplate = @"MMMd";
NSString *detailedString = [df stringFromDate:startDate toDate:
[trip.startDate dateByAddingNumberOfDays:endDate]];
Swift
let df = DateIntervalFormatter()
df.dateTemplate = "MMMd"
let stringDate = df.string(from: Date(), to: Date().addingTimeInterval(10000))
Documentation is straightforward:
If the range smaller than the resolution specified by the dateTemplate, a single date format will be produced. If the range is larger than the format specified by the dateTemplate, a locale-specific fallback will be used to format the items missing from the pattern.
For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours)
- The pattern jm will produce
for en_US, "7:56 AM - 7:56 PM"
for en_GB, "7:56 - 19:56"
- The pattern MMMd will produce
for en_US, "Mar 4"
for en_GB, "4 Mar"
If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes)
- The pattern jm will produce
for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM"
for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11"
- The pattern MMMd will produce
for en_US, "Mar 4-8"
for en_GB, "4-8 Mar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With