获取当月的开始日期

时间:2021-03-10 11:46:01

I want to get start date of current month in R. Now I use the following

我想在R中获得当月的开始日期。现在我使用以下内容

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=""))  #it return 2012-11-01

Is there any easy way to do this?

有没有简单的方法来做到这一点?

5 个解决方案

#1


23  

Yes, there is a one-liner for that using function cut:

是的,使用功能削减有一个单行:

cut(Sys.Date(), "month")
[1] 2012-11-01
Levels: 2012-11-01

#2


7  

Also one line using format function:

还有一行使用格式函数:

format(Sys.Date(),"01-%m-%Y")
[1] "01-06-2017"

#3


0  

as.Date(gsub(" ","",paste(format(Sys.Date(),"%Y-%m"),"-01")))

#4


0  

Using lubridate (also work with sec, min, hour, mon, year etc.)

使用lubridate(也适用于sec,min,hour,mon,year等)

library(lubridate)

dt <- Sys.Date()
day(dt) <- 01

dt
# [1] "2018-01-01"

#5


0  

lubridate's floor_date keeps it a Date

lubridate的floor_date将日期保留为日期

library(lubridate)

floor_date(Sys.Date(), "month")

#1


23  

Yes, there is a one-liner for that using function cut:

是的,使用功能削减有一个单行:

cut(Sys.Date(), "month")
[1] 2012-11-01
Levels: 2012-11-01

#2


7  

Also one line using format function:

还有一行使用格式函数:

format(Sys.Date(),"01-%m-%Y")
[1] "01-06-2017"

#3


0  

as.Date(gsub(" ","",paste(format(Sys.Date(),"%Y-%m"),"-01")))

#4


0  

Using lubridate (also work with sec, min, hour, mon, year etc.)

使用lubridate(也适用于sec,min,hour,mon,year等)

library(lubridate)

dt <- Sys.Date()
day(dt) <- 01

dt
# [1] "2018-01-01"

#5


0  

lubridate's floor_date keeps it a Date

lubridate的floor_date将日期保留为日期

library(lubridate)

floor_date(Sys.Date(), "month")