---
title: "Date, year, week conversion"
author: "Chi Zhang"
date: "2022-05-04"
output:
  rmarkdown::html_vignette:
    fig_width: 6
    fig_height: 6
vignette: >
  %\VignetteIndexEntry{Date, year, week conversion}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

These functions simplify working with dates and times across different formats.

Inputs can be numeric (e.g. `3`) or character (e.g. `"03"`, `"2020-03"`). The output type is controlled by the function suffix: functions ending in `_c` return a character, those ending in `_n` return a double.

```{r}
library(cstime)
library(magrittr)
```

## Which year and week is this date?

When called with no arguments, the functions return the isoyear or isoweek of today.

```{r}
date_to_isoyear_c()
date_to_isoyear_n()
date_to_isoweek_c()
date_to_isoweek_n()
# provide a date
date_to_isoyear_c('2021-01-01')
date_to_isoyear_n('2021-01-01')
date_to_isoweek_c('2021-01-01')
date_to_isoweek_n('2021-01-01')
date_to_isoyearweek_c('2021-08-11')
```

## Get isoyear and isoweek from an isoyearweek string

```{r}
isoyearweek_to_isoyear_c("2021-02")
isoyearweek_to_isoyear_n("2021-02")
isoyearweek_to_isoweek_c("2021-02")
isoyearweek_to_isoweek_n("2021-02")
```

The built-in dataset `dates_by_isoyearweek` provides a reference table. Here is how to subset it to specific years:

```{r}
yrwk_19_20 <- dates_by_isoyearweek[isoyear %in% c(2019, 2020)]
head(yrwk_19_20)
```
