Change day of the month in a Date to first day (01)
20,352
Solution 1
Yes, there is a one-liner for that using function cut
:
cut(Sys.Date(), "month")
[1] 2012-11-01
Levels: 2012-11-01
Solution 2
Also one line using format function:
format(Sys.Date(),"01-%m-%Y")
[1] "01-06-2017"
Solution 3
lubridate
's floor_date
keeps it a Date
library(lubridate)
floor_date(Sys.Date(), "month")
Solution 4
Using lubridate
(also work with sec
, min
, hour
, mon
, year
etc.)
library(lubridate)
dt <- Sys.Date()
day(dt) <- 01
dt
# [1] "2018-01-01"
Solution 5
as.Date(paste0(format(Sys.Date(), "%Y-%m"), "-01"))
Related videos on Youtube
Author by
Nandu
Updated on June 12, 2020Comments
-
Nandu almost 4 years
I want to set the day of month in a
Date
to start date of current month (01
). Now I use the following:currentDate <- Sys.Date() #for getting current system date eg:2012-11-06 formatDate <- format(currentDate, "%Y-%m") #it return 2012-11 startDate <- as.Date(paste(formatDate, "-01", sep = "")) # 2012-11-01
Is there any easy way to do this?
-
Admin over 11 yearsIf in Linux, you may use system("date",intern=T) to extract the date information as a string and then edit it.
-
-
Joseph Wood almost 7 yearsThis has the added benefit of keeping it in a date format as opposed to converting it to a factor via
cut
. -
Prradep over 6 years
class(format(Sys.Date(),"01-%m-%Y"))
results as"character"
. Butclass(cut(Sys.Date(), "month"))
results in"factor"
. So, bothe these approaches need to Date conversion apporach! -
sytech over 6 yearsIt would be useful to elaborate more on this solution, explaining how or why this solves the question being asked, or why it is better/different from the method described in the question or other answers.