2

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]

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
SKTLZ
  • 163
  • 1
  • 4
  • 12
  • If you've got to handle 1900, you've got problems. The 32-bit signed type can handle the range Dec 1901 .. Jan 2038, so handling the rest of 1901 and all of 1900 requires something different. Have you simply tried using negative numbers as the time stamp? – Jonathan Leffler Feb 18 '14 at 16:15
  • Easiest solution is 64 bits signed. Still, you might need to write your own `localtime` (Which can be fun - Amsterdam time used to be GMT +0h 19m 32,13s !) – MSalters Feb 18 '14 at 17:14
  • 1
    `time_t` is typically a signed integer type, and in many implementations the standard functions work correctly with negative values. But 32 bits only goes from 1901-12-13 to 2038-01-19. – Keith Thompson Feb 18 '14 at 17:16

3 Answers3

4

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".

Chad
  • 18,706
  • 4
  • 46
  • 63
0

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

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.

Michael
  • 878
  • 5
  • 17