Date, year, week conversion
Chi Zhang
2022-05-04
Source:vignettes/date_conversion.Rmd
date_conversion.Rmd
We create the following functions to make it easier to work with date and times in different formats.
For the input, we allow either a numeric (3) or string (“03”, “2020-03”).
For the output, the user need to specify whether numeric or string is required. Functions end with c
returns a character output and n
returns a double.
Which year/week is this date?
By default the functions returns the isoyear or isoweek of today.
date_to_isoyear_c()
#> [1] "2024"
date_to_isoyear_n()
#> [1] 2024
date_to_isoweek_c()
#> [1] "24"
date_to_isoweek_n()
#> [1] 24
# provide a date
date_to_isoyear_c('2021-01-01')
#> [1] "2020"
date_to_isoyear_n('2021-01-01')
#> [1] 2020
date_to_isoweek_c('2021-01-01')
#> [1] "53"
date_to_isoweek_n('2021-01-01')
#> [1] 53
date_to_isoyearweek_c('2021-08-11')
#> [1] "2021-32"
Get isoyear/isoweek from a isoyearweek
string
isoyearweek_to_isoyear_c("2021-02")
#> [1] "2021"
isoyearweek_to_isoyear_n("2021-02")
#> [1] 2021
isoyearweek_to_isoweek_c("2021-02")
#> [1] "02"
isoyearweek_to_isoweek_n("2021-02")
#> [1] 2
A list of isoyearweek
can be accessed in the following way.
yrwk_19_20 <- dates_by_isoyearweek[isoyear %in% c(2019, 2020)]
head(yrwk_19_20)
#> isoyear isoyearweek mon tue wed thu fri
#> 1: 2019 2019-01 2018-12-31 2019-01-01 2019-01-02 2019-01-03 2019-01-04
#> 2: 2019 2019-02 2019-01-07 2019-01-08 2019-01-09 2019-01-10 2019-01-11
#> 3: 2019 2019-03 2019-01-14 2019-01-15 2019-01-16 2019-01-17 2019-01-18
#> 4: 2019 2019-04 2019-01-21 2019-01-22 2019-01-23 2019-01-24 2019-01-25
#> 5: 2019 2019-05 2019-01-28 2019-01-29 2019-01-30 2019-01-31 2019-02-01
#> 6: 2019 2019-06 2019-02-04 2019-02-05 2019-02-06 2019-02-07 2019-02-08
#> sat sun weekdays
#> 1: 2019-01-05 2019-01-06 2018-12-31,2019-01-01,2019-01-02,2019-01-03,2019-01-04
#> 2: 2019-01-12 2019-01-13 2019-01-07,2019-01-08,2019-01-09,2019-01-10,2019-01-11
#> 3: 2019-01-19 2019-01-20 2019-01-14,2019-01-15,2019-01-16,2019-01-17,2019-01-18
#> 4: 2019-01-26 2019-01-27 2019-01-21,2019-01-22,2019-01-23,2019-01-24,2019-01-25
#> 5: 2019-02-02 2019-02-03 2019-01-28,2019-01-29,2019-01-30,2019-01-31,2019-02-01
#> 6: 2019-02-09 2019-02-10 2019-02-04,2019-02-05,2019-02-06,2019-02-07,2019-02-08
#> weekend
#> 1: 2019-01-05,2019-01-06
#> 2: 2019-01-12,2019-01-13
#> 3: 2019-01-19,2019-01-20
#> 4: 2019-01-26,2019-01-27
#> 5: 2019-02-02,2019-02-03
#> 6: 2019-02-09,2019-02-10
#> days
#> 1: 2018-12-31,2019-01-01,2019-01-02,2019-01-03,2019-01-04,2019-01-05,...
#> 2: 2019-01-07,2019-01-08,2019-01-09,2019-01-10,2019-01-11,2019-01-12,...
#> 3: 2019-01-14,2019-01-15,2019-01-16,2019-01-17,2019-01-18,2019-01-19,...
#> 4: 2019-01-21,2019-01-22,2019-01-23,2019-01-24,2019-01-25,2019-01-26,...
#> 5: 2019-01-28,2019-01-29,2019-01-30,2019-01-31,2019-02-01,2019-02-02,...
#> 6: 2019-02-04,2019-02-05,2019-02-06,2019-02-07,2019-02-08,2019-02-09,...