[英]How do I find the first and last day of next month?
如果我有給定的日期,如何找到下個月的第一天和最后幾天?
例如,
today <- as.Date("2009-04-04")
我想找到
# first date in next month
"2009-05-01"
# last date in next month
"2009-05-31"
您可以使用基數R執行此操作:
today <- as.Date("2009-04-04")
first <- function(x) {
x <- as.POSIXlt(x)
x$mon[] <- x$mon + 1
x$mday[] <- 1
x$isdst[] <- -1L
as.Date(x)
}
first(today)
#[1] "2009-05-01"
first(first(today)) - 1
#[1] "2009-05-31"
lubridate
為此目的提供了一些有用的工具。
library(lubridate)
today <- ymd("2009-04-12")
# First day of next month
first <- ceiling_date(today, unit = "month")
# Last day of next month
last <- ceiling_date(first, unit= "month") -1
first
#"2009-05-01"
last
#"2009-05-31"
這里有一些解決方案。 today
我們從問題中來進行測試。 在兩種情況下,輸入都可以是Date
類向量。
1)Base R Define函數fom
給出其Date
參數的月份的第一天。 使用它,我們可以獲得下個月的第一天和最后一個月的日期,如下所示。 我們使用的事實是,每個月的第一天之后的31天和62天一定是下個月和下個月后一個月中的日期。
fom <- function(x) as.Date(cut(x, "month"))
fom(fom(today) + 31)
## [1] "2009-05-01"
fom(fom(today) + 62) - 1
## [1] "2009-05-31"
2)yearmon yearmon
類對象在內部表示年份的年份和月份,1月為0,2月為1 / 12,3月為2/12,依此類推。 使用frac
參數as.Date.yearmon
指定月份到輸出的方式的分數。 默認值為frac = 0
,結果是輸出月的第一天,而frac = 1
表示該月的月末。
library(zoo)
as.Date(as.yearmon(today) + 1/12)
## [1] "2009-05-01"
as.Date(as.yearmon(today) + 1/12, frac = 1)
## [1] "2009-05-31"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.