Re: Error with the leap year

[email protected] (Zefram)
Newsgroups perl.datetime
Message-ID <[email protected]>
Michael G Schwern wrote:
>It does present a problem... how do you reliably say "same date next year"?

"Same date next year" is exactly what the original poster asked DateTime
for, by using the set_year method, and he got the correct answer: "there
isn't one".  Presumably what he actually wanted was "a year later",
which is a different question.  DateTime does support it:

	$dt->add(years=>1);

In the awkward case, it advances to March 1st:

	$ perl -MDateTime -lwe '
		$dt=DateTime->new(
			year=>2012,
			month=>2,
			day=>29,
			hour=>12,
			minute=>0,
			second=>0,
			time_zone=>"UTC",
		);
		$dt->add(years=>1);
		print $dt->iso8601;
	'
	2013-03-01T12:00:00

Of course, it has the downside that year addition isn't associative:
advancing from a February 29th by four years gives a different result
from advancing by one year four times.

>You can't add 365 days because that falls afoul of the leap year problem.

You can ask DateTime for that too:

	$dt->add(days=>365);

It's nicer, in that day addition *is* associative.  Of course, a quarter
of the time (when the 365 days spans a leap day), the 365-days-later
won't be the same-date-next-year.  Is that what you mean by the "leap
year problem"?

-zefram
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.