In my iOS app, I am getting the date format as 20231220T090000
for my calendar event in response. How will I convert this datetime from the date?
How to convert it to 20 Dec 2023, 9 AM
?
I can’t figure out the correct date format for it.
In my iOS app, I am getting the date format as 20231220T090000
for my calendar event in response. How will I convert this datetime from the date?
How to convert it to 20 Dec 2023, 9 AM
?
I can’t figure out the correct date format for it.
2
Answers
In your example,
20231220T090000
represents a date in the following format:And you’re trying to turn it into the following format:
You can use
DateFormatter
to parse the date from your input string and then re-format it into another date with the target format.Something like this could achieve what you’re looking for:
This can help you if you need the date format to be fixed. If you wish to display this date to a user, you should instead set
.dateStyle
and.timeStyle
to theoutFormat
.Rob’s answer is more detailed and informative.
You need a date formatter to parse the input:
By the way, you do not specify in what timezone the input string represents. Often it is in GMT/UTC/Zulu, in which case you would also include:
Note, this input string is likely in a fixed-format and, if so, it is important to set the
locale
of this date parsing formatter, as shown above, in case the user device is not using a Gregorian calendar.Anyway, you also need another date formatter to produced your output string:
No
locale
ortimeZone
is needed in this second formatter, as you undoubtedly want this output string formatted using the device default settings.As an aside, we would generally avoid using
dateFormat
for output strings, but rather usedateStyle
andtimeStyle
instead. (See the distinction between “user visible” and “fixed format” date strings in theDateFormatter
documentation.) Using date/time styles ensures that the date string is produced in a standard format, and one that is localized in accordance with the device settings, e.g.:Or, if you insist on this custom format (e.g., showing hours without minutes), you might consider using a localized date format string:
Anyway, now that you have your two formatters, you can parse the input and prepare the output string like so: