what do c++/STL programmers do for time programming?

A

Angus

There are the C runtime library functions of course, but are there any STL
time or date related functions? I couldn't find any.
 
S

Salt_Peter

There are the C runtime library functions of course, but are there any STL
time or date related functions? I couldn't find any.

Same as C, except these are declared in the std namespace.
Look at your <ctime> header
 
H

Howard Hinnant

"Angus said:
There are the C runtime library functions of course, but are there any STL
time or date related functions? I couldn't find any.

No, there are not. boost::date_time is being considered for a C++
technical report:

http://www.boost.org/doc/html/date_time.html

For simple date applications without much I/O needs I prefer my
homegrown date class:

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

What I like about it is the difficult-to-get-wrong construction syntax:

date d = may/29/2007; // ok
date d = 29/may/2007; // doesn't compile
date d = day(29)/may/2007; // ok
date d = day(29)/5/2007; // ok

In general, if it compiles, you've got a non-ambiguous date
specification following one of these patterns:

d/m/y
m/d/y
y/m/d

There's no danger of getting Feb. 1 and Jan 2 mixed up:

date d(1, 2, 2007); // doesn't compile
date d = 1/2/2007; // doesn't compile
date d = jan/2/2007; // ok
date d = day(1)/2/2007; // ok
date d = day(1)/feb/2007; // ok
date d = year(2007)/feb/1; // ok

And then there's the usual date arithmetic and the ability to specify
holidays like Mother's Day (US) as:

date d = 2*sun/may/2007; // second Sunday in May, 2007

Last days of the month, or last weekdays of the month are similarly easy:

Print out last day of each month for 2004:

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

Print out last Saturday of every month in 2004:

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

It is a relatively light-weight value class with only two files (a
header and source):

class date
{
private:
unsigned long jdate_;
unsigned short year_;
unsigned char month_;
unsigned char day_;
...
};

(sizeof(date) == 8 on my platform)

Feel free to use it.

-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
474,294
Messages
2,571,511
Members
48,199
Latest member
MarielIzzo

Latest Threads

Top