Search code examples
r

How to get current week start date ( Monday ) and End Date ( Sunday) in R


How to get current week start date ( Monday ) and End Date ( Sunday) in R.

My business weeks start from Monday and ends on Sunday.

How do i retrieve Start Date and End Date from my current date.

Eg. Curent date is 18-07-2020. How to retrieve Monday Date ( 18-07-2020) and Sunday Date (19-07-2020)

My Code :

library(lubridate)
library(mailR)
library(htmlTable)
library(DBI)

todays_date <- Sys.Date()
stdt <- floor_date(todays_date, 'week') + 1
lsdt <- floor_date(todays_date, 'week') + 7

If I execute the above code on Sunday, it falls on to next week. Any workaround to make the code to run on Sunday as well, by considering Monday to Sunday as working days.


Solution

  • You can use lubridate's floor_date and ceiling_date with unit as "week". By default week starts on a Sunday in lubridate so to get start date as Monday we need to add 1 in floor_date.

    library(lubridate)
    todays_date <- as.Date('2020-07-18')
    floor_date(todays_date, 'week') + 1
    #[1] "2020-07-13"
    
    ceiling_date(todays_date, 'week')
    #[1] "2020-07-19"