0

I basically have this code right now and I am trying to format by having a new line in between but it doesn't give me a new line. Am I doing it correctly?

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_DB"];
dateFormatter.locale = twoHourLocale;
formatString = [NSDateFormatter dateFormatFromTemplate:@"EEEE \n hh:mm" options:0 locale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:formatString];
Josh
  • 99
  • 2
  • 9
  • 1
    Possible duplicate of [Converting a date format in objective C](https://stackoverflow.com/questions/6724180/converting-a-date-format-in-objective-c) – jlewkovich Mar 04 '19 at 21:09
  • @JLewkovich It's not a duplicate; this question concerns the behavior of ``-dateFormatFromTemplate:locale:options:`, whereas the suggested dupe is just a matter of a bad format string. – Caleb Mar 04 '19 at 22:23

2 Answers2

1

I basically have this code right now and I am trying to format by having a new line in between but it doesn't give me a new line. Am I doing it correctly?

The point of calling -dateFormatFromTemplate:locale:options: is to get back a format string that's properly formatted for the specified locale. That is, the method looks at the date components you specify and arranges them to suit the local custom, like "Jan 2 2019" in the US, but "2 Jan 2019" in Europe. I think it basically ignores any parts of the template that it doesn't recognize as a date component specifier. If it's moving the date components around, how would it know where to place the non-date parts that it doesn't know about?

If you don't care about different locales and just want a date that has a newline in it, then you can skip that method and just create the template string yourself:

formatString = @"EEEE \n hh:mm";
[dateFormatter setDateFormat:formatString];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", dateString);

The code above will log the current date with a newline between the weekday and the time, so -stringFromDate: will happily use your format string and keep the newline.

If you do care about locales but still want the newline, you'll have to either create your own locale-specific date format strings, or call -dateFormatFromTemplate:locale:options: and then insert the newline at the right spot in the result.

Caleb
  • 124,013
  • 19
  • 183
  • 272
0

It seems it should work based on this question: Format date on 2 lines

However, that's in swift, so there could be different implementation details. Worst case scenario, you can split your 'EEEE' and 'hh:mm' into 2 different formatters and concatenate them.

johnny
  • 1,434
  • 1
  • 15
  • 26