I need a simple way to format dates by different country formats. In the ideal case make one setup and use it everywhere in the code. Let's say for EN and FR formats it should be: YYYY-MM-DD (England) and DD-MM-YYYY (France)
# This requires extra work. Each time ask the wrapper
format_date <- function(date_obs, country_code) {
if(country_code == "en") result <- format(date_obs, format = "%Y-%m-%d")
if(country_code == "fr") result <- format(date_obs, format = "%d-%m-%Y")
result
}
format_date(today(), "en")
format_date(today(), "fr")
# I need this kind of solution
Sys.setlocale(date_format = '%d-%m-%Y')
print(today()) # <<- should be in French format
my_format_date <- function(date_obs, country_code) {
if(country_code == "en") result <- format(date_obs, format = "%Y-%m-%d")
if(country_code == "fr") result <- format(date_obs, format = "%d-%m-%Y")
result
}
my_lang <- 'fr' # <<- should be in French format from now on
print.Date <- purrr::partial(my_format_date, country_code=my_lang)
print(lubridate::today())
#> [1] "07-02-2023"
my_lang <- 'en' # <<- and now in English format until reset
print.Date <- purrr::partial(my_format_date, country_code=my_lang)
print(lubridate::today())
#> [1] "2023-02-07"
Created on 2023-02-07 with reprex v2.0.2
HI, just a comment to say that your solution is even better than you gave it credit for, because the print.Date definition via partial is lazy, it will look for my_lang each time. so
my_lang <- 'fr' # <<- should be in French format from now on
print.Date <- purrr::partial(my_format_date, country_code=my_lang)
print(lubridate::today())
#> [1] "07-02-2023"
my_lang <- 'en' # <<- and now in English format until reset
print(lubridate::today())
#> [1] "2023-02-07"
this works too (i.e. dropping the second print.Date <-