lubridate icon indicating copy to clipboard operation
lubridate copied to clipboard

`update()` function gives strange results when changing to the beginning of a leap year

Open ShanikaLW opened this issue 4 years ago • 3 comments

When the update() function is used to change the year and yday it gives strange results when the actual year is a leap year.

What is the reason for this behavior?

x <- ymd("2009-09-02")
update(x, year = 2008, yday = 1)
[1] "2008-01-02" # should be "2008-01-01"

x <- ymd("2009-02-28")
update(x, year = 2008, yday = 1)
[1] "2008-01-01" # it works

x <- ymd("2009-03-01")
update(x, year = 2008, yday = 1) 
[1] "2008-01-02" # doesn't work

year(x) <- 2008
yday(x) <- 1
x
[1] "2008-01-01" # as expected.

ShanikaLW avatar Mar 03 '21 11:03 ShanikaLW

This seems to occur for all leap years, and is likely the purpose of this commented line: https://github.com/tidyverse/lubridate/blob/6f26b02de432cd9373ad4ce7766c36eacfc29918/src/update.cpp#L304

Looks like it was removed when resolving issue #567. The leap year code was added by @vspinu to resolve issue #319 of which this is issue looks identical to.

Perhaps there is a better way to solve #567?

mitchelloharawild avatar Mar 09 '21 12:03 mitchelloharawild

@mitchelloharawild thanks for the refined trace. Looks like a regression indeed.

vspinu avatar Mar 10 '21 15:03 vspinu

Works with clock's year-day type since, by design, you can't update multiple components at once

library(clock)
library(magrittr)

x <- year_month_day(2009, 9, 2) %>%
  as_year_day()

x
#> <year_day<day>[1]>
#> [1] "2009-245"
 
x <- x %>%
  set_year(2008) %>%
  set_day(1)

x
#> <year_day<day>[1]>
#> [1] "2008-001"

as.Date(x)
#> [1] "2008-01-01"

Created on 2021-05-25 by the reprex package (v1.0.0)

DavisVaughan avatar May 25 '21 14:05 DavisVaughan

Fixed in devel

library(lubridate, warn.conflicts = F)
#> Loading required package: timechange

x <- ymd("2009-09-02")
update(x, years = 2008, ydays = 1)
#> [1] "2008-01-01"

x <- ymd("2009-03-01")
update(x, years = 2008, ydays = 1) 
#> [1] "2008-01-01"

Created on 2022-11-02 with reprex v2.0.2

vspinu avatar Nov 02 '22 21:11 vspinu