Robert's Data Science Blog

Weekdays in English

Consider a datetime:

(t <- as.POSIXct("2020-02-29 12:34:56"))
## [1] "2020-02-29 12:34:56 CET"

I am interested in the weekday of this datetime and I want it to be in English – regardless of the computer executing the command.

My real problem is a computer where some settings are in Danish and where I do not have sufficient privileges to change them.

This blog post is made with the blogdown package on a computer where everything is in English and where I have sufficient permissions, so the unexpected outputs are copied in.

Locale

Some results in R are printed based on the locale on the computer. For time related printing this is set by LC_TIME. On my English computer the value is

Sys.getlocale("LC_TIME")
## [1] "en_DK.UTF-8"

On my Danish computer the value is “Danish_Denmark.1252”.

The base R command weekdays rely on LC_TIME and on my Danish computer I get this weekday:

> weekdays(t)
[1] "lørdag"

Lubridate

I find the function wday from the lubridate package to be a more flexible alternative because the value of locale can be set as an argument.

On my English computer I don’t need to set the locale:

lubridate::wday(t, label = TRUE, abbr = FALSE, week_start = 1)
## [1] Saturday
## 7 Levels: Monday < Tuesday < Wednesday < Thursday < Friday < ... < Sunday

On my Danish computer the output is

> lubridate::wday(t, label = TRUE, abbr = FALSE, week_start = 1)
[1] lørdag
Levels: mandag < tirsdag < onsdag < torsdag < fredag < lørdag < søndag

With sufficient permissions it should be possible to set the locale to a variant of English, but unfortunately I get in trouble on my Danish computer:

> lubridate::wday(t, label = TRUE, abbr = FALSE, week_start = 1, locale = "English United States")
Fejl i Sys.setlocale("LC_TIME", locale) : 
  (konverteret fra advarsel) OS reports request to set locale to "English United States" cannot be honored

I have to rely on something really old school:

lubridate::wday(t, label = TRUE, abbr = FALSE, week_start = 1, locale = "C")
## [1] Saturday
## 7 Levels: Monday < Tuesday < Wednesday < Thursday < Friday < ... < Sunday