SKTLZ
SKTLZ

Reputation: 183

Date handling before 1970 c++

I was wondering what is the best thing to do here. I was given an assignment and I have to update a Date class that uses Ctime.

The class must now work for date before 1970. I was looking around and I didn't find much...

So I guess my question is what would be the best way to achieve that?

Date Range from [1970-2037] to [1900-2037]

Upvotes: 2

Views: 3968

Answers (3)

Michael
Michael

Reputation: 958

How about a date class that stores an internal std::tm datetime object and the total seconds since (or before) Jan 1, 1970 as a time_t. The members of tm are all ints and time_t should be 64bit everywhere (I hope), so in theory that should cover all the times you could consider.

In the constructor of your class you'd need to compute those total seconds and the only standard library function that seems to do that is mktime. Unfortunately this one only works for dates after Jan 1, 1970.

One possible workaround... add a really big number to the year and work with that internally.

#include <ctime>
#include <iostream>
class CustomDateTime {
  const int MKTIME_DELTA = 100000;
  std::tm _datetime;
  std::time_t _total_seconds;
public:
  CustomDateTime(int year, int mon, int day, int hour, int min, int sec) {
    _datetime.tm_year = year - 1900 + MKTIME_DELTA;
    _datetime.tm_mon  = mon - 1;
    // copy day, hour, min, sec
    _total_seconds = std::mktime(&_datetime);
  }
  bool operator==(const CustomDateTime& rhs) { 
    return _total_seconds == rhs._total_seconds;
  }
  void print() {
    std::cout << _datetime.tm_year + 1900 - MKTIME_DELTA << ':'
      << _datetime.tm_mon + 1 << _datetime.tm_mday << '\n';
  }
};

That should cover all years between 1970 - MKTIME_DELTA = -98030 and the far far future.

Upvotes: 0

Chad
Chad

Reputation: 19052

Assuming you mean CTime from MFC, if you enable OLE you can use COleDateTime as a drop-in replacement. Per the documentation, it supports dates "from January 1, 100, through December 31, 9999".

Upvotes: 4

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136475

You could store the date as a signed integer number of days since 1970-01-01 or any other epoch. Negative dates would be the date before 1970.

Or you could use Boost.Date_Time library.

Upvotes: 0

Related Questions