Yet another date class, public-sourced

H

Howard Hinnant

I'm tossing my date class into the public domain because I'm tired of it
sitting around gathering dust. It was first created over a decade ago
and has been evolving by bits and pieces since then.

Here is the doc with the source+test linked off of it:

http://home.twcny.rr.com/hinnant/cpp_extensions/Gregorian_date.html

It has a relatively small footprint (2 words typical). It has a cute
construction interface that makes it very difficult, if not impossible,
to mistakenly create the wrong date:

date d1 = mar/19/2006;
date d2 = day(19)/3/2006;
date d3 = year(2006)/mar/19;

These all refer to the same day. Ambiguous date constructions fail at
compile time. Out of range date constructions fail at run time. It is
not possible for a date to hold an invalid value.

Date arithmetic is fully supported, including (for example) iterating
over the last saturday of each month in a year:

for (date d = last*sat/jan/2004, end = last*sat/dec/2004;
d <= end; d += month(1))
std::cout << d << '\n';

01/31/04
02/28/04
03/27/04
04/24/04
05/29/04
06/26/04
07/31/04
08/28/04
09/25/04
10/30/04
11/27/04
12/25/04

I/O is punted to the std::time_get/time_put facets.

It is a small package, 1 header, 1 source totaling less than 700 lines
of code. It has a fairly minimal interface:

* There's a wide choice of how to construct dates, but none of them
will allow an invalid date to be constructed.

* There is date arithmetic including dates +/- days, months or years,
and the notion of "last" applying to "day of the month" or "weekday of
the month". You can not compute an invalid date (an exception occurs if
you try).

* Five member observers:

int day() const;
int month() const;
int year() const;
int day_of_week() const;
bool is_leap() const;

* There are no mutators except for the arithmetic operators (e.g. +=).

If it is useful or amusing for you, great. If not, there's plenty more
choices out there (boost::date for example is a good one).

-Howard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top