0

I am having trouble on the following code:

let dateFormatter = DateFormatter()
dateFormatter.locale = locale
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short

dateFormatter.doesRelativeDateFormatting = true
dateFormatter.amSymbol = "a" // not working if above set to true
dateFormatter.pmSymbol = "p"

let str = dateFormatter.string(from: Date())

output => str String "Today, 12:15 PM"

The amSymbol and pmSymbol setters work if doesRelativeDateFormatting = false, With doesRelativeDateFormatting set to true, the amSymbol and pmSymbol setters don't seem to make any difference.

Do you think this is a SDK bug or perhaps I miss something?

Sean
  • 2,967
  • 2
  • 29
  • 39
  • I think your best option is to replace "AM/PM" in your final string. IMO you should accept whatever format it uses. – Leo Dabus Aug 10 '21 at 19:56

1 Answers1

0

Setting the dateFormatter.dateStyle = .none makes it work but I suppose you need the dateStyle to print dateString in Today, 12:15 p format. So, I used two separate dateFormatters, one for the dateStye and the other for the timeStyle.

let dateFormatterForDate = DateFormatter()
dateFormatterForDate.dateStyle = .short
dateFormatterForDate.doesRelativeDateFormatting = true

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.timeStyle = .short
dateFormatter.amSymbol = "a"
dateFormatter.pmSymbol = "p"

let str = "\(dateFormatterForDate.string(from: Date())), " + "\(dateFormatter.string(from: Date()))"
print(str)

Output: Today, 1:15 a

  • Not every locale uses a comma – Leo Dabus Aug 10 '21 at 19:55
  • IMO the final date string can be customised as per the need. – ayushmahajan Aug 11 '21 at 04:13
  • 1
    You should never define how the user should see their dates IMO. Always respect the device locale and settings. This is how you should display the date to the user. https://stackoverflow.com/a/28347285/2303865. No customization other than the date/time style length and which timezone you want to display. Custom string mixing two date formatters doesn't make any sense and not practical. – Leo Dabus Aug 11 '21 at 04:34
  • I believe the date can be displayed in any format what matters the most is the date should be easy to read and in the correct timeZone. Setting the `DateFormatter's dateFormat` is a convenient way to add a custom formatting and is used by tons of iOS apps. – ayushmahajan Aug 11 '21 at 09:07