user7423463
user7423463

Reputation:

How to get date string with capitalized first letter?

I am trying to localize string.

In English I am getting a date string like "Friday, Jun 26" but in Spanish it's like "jueves, jun 25".

The first letter is small but I am trying to get a capitalized first letter just like English.

Below is my code.

let longDateFormatter = DateFormatter()
longDateFormatter.dateFormat = "EEEE, MMM d"
longDateFormatter.locale = Locale(identifier: "es")

Is there any way to get date with first letter capitalized?

Upvotes: 2

Views: 1641

Answers (1)

Duncan C
Duncan C

Reputation: 131408

Apparently Spanish does not capitalize the names of months and days of the week like we do in English. Thus the format you are getting is correct for Spanish, and you should stop trying to change it. (in essence, this is an x/y problem.)

See this link: https://www.spanishdict.com/answers/181002/do-months-need-to-be-capitalized-in-spanish#:~:text=Spanish%20does%20NOT%20capitalize%3A&text=%3F-,Calendar%3A%20Names%20of%20the%20days%20of%20the,and%20months%20of%20the%20year.&text=%3F-,Nationality%3A%20Although%20names%20of%20countries%20and%20cities%20are%20capitalized%2C%20words,derived%20from%20them%20are%20not.

If you want to do something different than the correct localization for Spanish you will need to take the output from the Spanish localization and manipulate it. You could simply use longDateFormatter.string(from: date).capitalized, which would capitalize every word in the resulting date string.

let longDateFormatter = DateFormatter()
longDateFormatter.dateFormat = "EEEE, MMM d"
longDateFormatter.locale = Locale(identifier: "es")

let output = longDateFormatter.string(from: Date()).capitalized
print(output)

Yields

Viernes, Jun 26

But again, that is the WRONG way to display dates in Spanish. It is every bit as wrong as displaying "friday, june 26" in English.

Edit on 26 October 2023:

Note that as mentioned by @user28434'mstep, for localized date conversions, it's better to set the formatter's format string using setLocalizedDateFormatFromTemplate. With that change, the code above (without forcing the output to be capitalized) would look like this:

let longDateFormatter = DateFormatter()
longDateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d")
longDateFormatter.locale = Locale(identifier: "es")
    
let output = longDateFormatter.string(from: Date())
print(output)

(In this particular case it seems that longDateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d") and longDateFormatter.dateFormat = "EEEE, MMM d" yield the same results, but using setLocalizedDateFormatFromTemplate for localizable formatters is still best practice.)

Upvotes: 4

Related Questions