Formatting time object specifying LC_TIME without changing locale

Viewed 56

Is there a way to format a POSIXct object in R and specifying the LC_TIME in that call?

Ie I have this code which returns the object in the German format

t <- Sys.time()
fmt <- "%a, %d %b %Y %H:%M:%S GMT"
format(t, fmt)
#> [1] "Mi, 23 Mrz 2022 14:57:50 GMT"

Sys.getlocale("LC_TIME")
#> [1] "German_Germany.1252"

The format I want can be achieved by setting the LC_TIME, but this is not what I want. Instead I want to find a solution without changing the options of my R session or my locale.

Sys.setlocale("LC_TIME", "C")
format(t, fmt)
#> [1] "Wed, 23 Mar 2022 14:57:50 GMT"
# correct output, but changing the locale :(

Ideally, I want something like format(t, fmt, LC_TIME = "C") or similar with minimal external dependencies and not changing anything else...

1 Answers

I couldn't find a perfect solution but there is a workaround using local(), depending on your purposes. local() let you define variables as in a function, so your global environment won't be disturbed.

fmt <- "%a, %d %b %Y %H:%M:%S GMT"
local({
  locale <- Sys.getlocale("LC_TIME")
  Sys.setlocale("LC_TIME", "C")
  final_date <- format(Sys.time(), fmt)
  Sys.setlocale("LC_TIME", locale)
  return(final_date)})
#> [1] "Wed, 25 May 2022 12:03:36 GMT"

Unfortunately the system locale is changed so you should use Sys.setlocale("LC_TIME", locale) at the end to turn it back. The advantage of this method is that you can get what you want with zero changes in your variables (the variable locale would be created otherwise).

Related