Skip to content

Commit ad8d409

Browse files
authored
Floor double Dates before casting to integer with duration_days() (#194)
We are generally a bit more lax with Dates and POSIXct. For POSIXct, we already floor to get rid of fractional seconds, so this just adds similar behavior for Dates and fractional days.
1 parent 455d97e commit ad8d409

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

R/date.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
as_sys_time.Date <- function(x) {
33
names <- names(x)
44
x <- unstructure(x)
5+
if (is.double(x)) {
6+
x <- floor(x)
7+
}
58
x <- duration_days(x)
69
new_sys_time_from_fields(x, PRECISION_DAY, names)
710
}

tests/testthat/test-date.R

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,26 @@ test_that("invalid dates must be resolved when converting to a Date", {
55
expect_snapshot_error(as.Date(year_month_day(2019, 2, 31)))
66
})
77

8+
# ------------------------------------------------------------------------------
9+
# as_sys_time()
10+
11+
test_that("converting to sys-time floors fractional dates (#191)", {
12+
x <- new_date(c(-0.5, 1.5))
13+
y <- new_date(c(-1, 1))
14+
15+
expect_identical(as_sys_time(x), as_sys_time(y))
16+
expect_identical(as.Date(as_sys_time(x)), y)
17+
})
18+
19+
test_that("converting to sys-time works with integer storage dates", {
20+
# These can occur from `seq.Date(from, to, length.out)`
21+
x <- structure(1L, class = "Date")
22+
y <- new_date(1)
23+
24+
expect_identical(as_sys_time(x), as_sys_time(y))
25+
expect_identical(as.Date(as_sys_time(x)), y)
26+
})
27+
828
# ------------------------------------------------------------------------------
929
# as_weekday()
1030

0 commit comments

Comments
 (0)