# Dates and Times – Simple and Easy with lubridate exercises (part 1)

August 15, 2016
By

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

As in any programming language, handling date and time variables can be quite frustrating, since, for example, there is no one single format for dates, there are different time zones and there are issues such as daylight saving time.

Base R provides several packages for handling date and time variables, but they require mastering cumbersome syntax.

In order to solve all those issues and more, R package “lubridate” was created. This package on one hand has a very easy and intuitive syntax and on the other hand has functions that cover a wide range of issues related to dates and times.

In this first part in the series of lubridate exercises, the basic functionality of the package is covered.

`install.packages("lubridate")`
`library(lubridate)`

Answers to the exercises are available here.
If you have different solutions, feel free to post them.

## Parsing Date-times

The ymd() series of functions are used to parse character strings into dates.
The letters y, m, and d correspond to the year, month, and day elements of a date-time.

Exercise 1
Populate a variable called “start_date” with a date representation of string “23012017”

Exercise 2
Use the lubridate function `today` to print the current date

Exercise 3
Extract the `year` part from the “start_date” variable created on exercise 1

Exercise 4
Extract the `month` part from the “start_date” variable created on exercise 1

Exercise 5
Extract the `day` part from the “start_date” variable created on exercise 1

Exercise 6
Set the `month` in variable “start_date” to February

Exercise 7
Add 6 `days` to variable “start_date”.
Did you notice what happened to the month value?

Exercise 8
Substract 3 `months` from variable “start_date”

Populate a field called concatenated_dates with a vector of dates containing the following values:
“31.12.2015”, “01.01.2016”, “15.02.2016”

Calculate in a short and simple way the addition of 1 thru 10 days to “start_date” variable

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...