---
output: html_document
---

Dates and times are difficult!

* Does every year have 365 days?
* Does every day have 24 hours?
* Does every minute have 60 seconds?

```{r}
library(tidyverse)
library(nycflights13)
library(lubridate)
```

* A date. Tibbles print this as `<date>`.
* A time within a day. Tibbles print this as `<time>`.
* A date-time is a date plus a time: it uniquely identifies an instant in time (typically to the nearest second). Tibbles print this as `<dttm>`. Elsewhere in R these are called `POSIXct`.

```{r}
today()
str(today())

now()
str(now())
tibble(now = now())
```

From a string:

```{r}
ymd("2017-01-31")
mdy("January 31st, 2017")
dmy("31-Jan-2017")
ymd_hms("2017-01-31 20:11:59")

strptime("31/1-2017", format = "%d/%m-%Y") # ?strptime
fast_strptime("31/1-2017", format = "%d/%m-%Y")
strptime("31/1-2017", format = "%d/%m-%Y", tz = "UTC") # ?strptime
```

Arithmetic:

```{r}
x = ymd_hms("2017-11-24 10:11:59")
x

lubridate::round_date(x, unit = "second")

lubridate::round_date(x, unit = "hour")
lubridate::ceiling_date(x, unit = "hour")

lubridate::round_date(x, unit = "month")
lubridate::floor_date(x, unit = "month")


h_christmaseve <- ymd_hms("2018-12-24 18:00:00") - now()
h_christmaseve
str(h_christmaseve)

d_christmaseve <- as.duration(h_christmaseve)
d_christmaseve
str(d_christmaseve)

x + 10
x + dseconds(10)
x + dweeks(10)
x + ddays(1:3)

x + dseconds(10) + dweeks(10)
```


From individual date-time components:

```{r}
flights %>% 
  select(year, month, day, hour, minute)

d <- flights %>% 
  select(year, month, day, hour, minute) %>% 
  mutate(departure = make_datetime(year, month, day, hour, minute))
d

ggplot(d, aes(departure)) + 
  geom_freqpoly(binwidth = 86400) # 86400 seconds = 1 day

d %>% 
  filter(departure < ymd(20130102)) %>% 
  ggplot(aes(departure)) + 
  geom_freqpoly(binwidth = 600) # 600 s = 10 minutes
```


```{r}
d %>% 
  mutate(wday = wday(departure))

d %>% 
  mutate(wday = wday(departure, label = TRUE))

d %>% 
  mutate(wday = wday(departure, label = TRUE)) %>% 
  ggplot(aes(wday)) +
  geom_bar()
```

## Exercise

Write a function that given your birthday (as a text string), returns how old you are in years.

How old are you on Dec 24, 2018 (at 18:00)?



