Somjit Glin-Jan
Somjit Glin-Jan

Reputation: 81

How to get localized "One Letter" weekday abbreviations in Dart?

If I do this

DateTime dateTime = DateTime(2022, 5, 1); // Sunday
print(DateFormat("E").format(dateTime));

Sun will be printed out to the console. Which is what I expected.

This also works if I change the system language.

How to printout the localized One Letter weekday abbreviation?

e.g. M T W T F S S

I thought I can get first letter using "substring", but it won't be correct for all languages. For example, Spanish weekdays are: Lunes, Martes, Miércoles, Jueves, Viernes, Sábado and Domingo, and first letter for "Miércoles" is X instead of M to difference it from "Martes".

In Java you could do something like this to get the One Letter abbreviation:

new SimpleDateFormat("EEEEE", Locale.getDefault());
simpleDateFormat.format(date);

For Spanish the output would be L M X J V S D

Upvotes: 5

Views: 2469

Answers (2)

igorz
igorz

Reputation: 181

Depending on a use case, like a calendar header, it might be actually better to use standalone weekday format.

One-letter standalone format is supported with custom pattern ccccc:

var dateTime = DateTime(2022, 5, 1); // Sunday

for (int i = 0; i < 7; i++) {
  print(DateFormat("ccccc").format(dateTime));

  dateTime = dateTime.add(Duration(days: 1));
}

That prints: S M T W T F S

Upvotes: 6

Somjit Glin-Jan
Somjit Glin-Jan

Reputation: 81

I found the solution to my question. Maybe its helpful to somebody.

var wd = DateFormat.EEEE().dateSymbols.NARROWWEEKDAYS;
print(wd);

The output for Spanish language [D, L, M, X, J, V, S]

This works with all languages i have tested (Japanese, German, English, Polish, Spanish, Italian etc.)

Upvotes: 3

Related Questions