4

I usually set my working environment in English although it is not my mother tongue, because most dates I use in input are this way.

However, I sometimes to output a date in a long format in another language, usually French.

library(lubridate) 
today()
> today()
[1] "2020-12-22"

That is, I would like a function that gives :

DateInLongFormatInFrench(today)
[1] "Mardi 22 décembre"

Which is the French for "Tuesday, December the 22th". And I would like the solution not to change the language setting for the whole program, but just this instance.

I have found a lot of post on how to read dates, but not so much on how to output them

Anthony Martin
  • 767
  • 1
  • 9
  • 28
  • It would depend on your locale settings. Otherwise, `format(today(), '%A %d %B')` should work – akrun Dec 22 '20 at 16:55
  • 4
    The `withr` package is useful for changing the locale settings for a single line. (Though I'm having trouble on Windows with French---you may have an easier time if you're not on windows.) But if you can find the right locale settings / your OS is more compliant than mine, something like `withr::with_locale("LC_TIME" = "fr_FR", format(today(), '%A %d %B'))` should work. – Gregor Thomas Dec 22 '20 at 17:00

1 Answers1

4

Convert dates to strings using format.Date

format(<my_date>, "%A %d %B")

You must have your locale set to a Francophone region, e.g.

Sys.setlocale("LC_TIME", "fr_FR")

If you need to do this in isolation:

frenchDate <- function(x) {
  locale <- Sys.getlocale("LC_TIME")
  
  # when function exits, restore original locale
  on.exit(Sys.setlocale("LC_TIME", locale))

  Sys.setlocale("LC_TIME", "fr_FR")

  format(x, "%A %d %B")
}
bcarlsen
  • 1,381
  • 1
  • 5
  • 11
  • note for future readers that the locale also has to be available: I get "OS reports request to set locale to 'fr_FR' cannot be honored", presumably because it's not installed – Ben Bolker Dec 22 '20 at 17:06
  • 2
    I think this is the right way to go. It can be generalized a little if desired, with `function(x, format = "%A %d %B", locale = "fr_FR") { ...; format(x, format = format); }`, thereby allowing non-hard-coded formats and locales. (That suggests a name like `format_locale` or similar.) – r2evans Dec 22 '20 at 17:08
  • Yeah, locale names are OS-dependent. `?locales` has a pretty good rundown. – bcarlsen Dec 22 '20 at 17:16