Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove 'at' from formatted date string?

This is the date formatter setup:

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .medium

Expected output:

Aug 13, 2017 6:04:11 PM

Current output:

Aug 13, 2017 at 6:04:11 PM

How can the 'at' word be removed ideally without specifying a format string and where does it come from?

With Austrian German locale:

dateFormatter.locale = Locale(identifier: "de_AT")
13.08.2017, 18:04:11

With US English locale:

dateFormatter.locale = Locale(identifier: "en_US")
Aug 13, 2017 at 6:04:11 PM
like image 828
Andras Hatvani Avatar asked May 30 '26 00:05

Andras Hatvani


1 Answers

One option would be to make two separate conversions, one setting only dateStyle = .medium, and one setting only timeStyle = .medium, and then concatenate the result. But I don't know if a

<date><space><time>

format makes sense in all languages and locales.

A better approach is to use setLocalizedDateFormatFromTemplate:

dateFormatter.setLocalizedDateFormatFromTemplate("MMM dd yyyy jj:mm:ss")

This comes close to what you wanted, and is guaranteed to give a sensible result for all locale settings. Here some examples.

en_US:   Aug 13, 2017, 6:33:54 PM
de:      13. Aug. 2017, 18:33:54
ja:      2017年8月13日 18:33:54

Note the usage of jj format for the hour, this will be interpreted as HH (24 hour format) or hh (12 hour AM/PM format), depending on the locale.

like image 142
Martin R Avatar answered Jun 02 '26 09:06

Martin R