Subtracting months - issue with last day of month?

后端 未结 3 1098
暗喜
暗喜 2020-12-10 15:50

Quick question on dates in R. Check out this snippet of code:

Sys.Date() - months(3)
# [1] \"2013-12-31\"
Sys.Date() - months(18)
# [1] NA

3条回答
  •  不思量自难忘°
    2020-12-10 16:30

    The solution provides forward months exactly, i.e. 28Feb %m+% gives 28Mar, which is not ideal if working with month end data.

    To adjust the top to always give you the last day of the month, use the following code:

    ceiling_date((as.Date("2014-02-28") %m+% months(1)),"month")-days(1)
    
    > "2014-03-31"
    

提交回复
热议问题