Newbie Question: Working with dates

E

Erik

Is there a variable for storing dates and how can I count with dates:
For example, how do I code how much days there are between 01-01-2005
and 03-03-2005?
 
E

Eric Sosman

Erik said:
Is there a variable for storing dates and how can I count with dates:
For example, how do I code how much days there are between 01-01-2005
and 03-03-2005?

The library provides some rudimentary support for date
computations, but they're not really very well-supported by
C as such. Here's something you could try:

#include <time.h>
...
struct tm date1 = { 0 }, date2 = { 0 };
time_t time1, time2;
int days;

date1.tm_year = 2005 - 1900;
date1.tm_mon = 1 - 1;
date1.tm_mday = 1;
date1.tm_isdst = -1;
time1 = mktime(&date1);

date2.tm_year = 2005 - 1900;
date2.tm_mon = 3 - 1;
date2.tm_mday = 3;
date2.tm_isdst = -1;
time2 = mktime(&date2);

days = difftime(time2, time1) / (60.0 * 60.0 * 24.0);

Unfortunately, this is not guaranteed to work as you'd hope.
Different implementations of C support different ranges of
dates, and either or both of the mktime() calls could fail.
(All implementations I know of can handle dates in 2005, but
if you start trying to work with dates in 2100 or 1776 your
results may be disappointing.) Also, the "divide by one day's
worth of seconds" step is a little too naive: Most days are
24 hours long, but many places observe one 23-hour and one
25-hour day each year -- some C implementations can handle
this adjustment, others can't. Days of 24:00:01 or 23:59:59
are also possible, and (believe it or not) some systems are
actually *forbidden* to pay attention to this!

The method illustrated above will work reasonably well on
many systems for a limited range of dates most of the time,
but that's about all that can be said for it.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top