I'm implementing this date class based on <ctime>
I'll appreciate your comments, critics and advice.
Please review, thank you!.
Date.h
/*
* Date.h
*
* Usage:
* Create object, and then call Set(day, month, year)
* Throws invalid argument exception if Teb 29th is set with the wrong year (is not leap year)
* TODO: throw invalid argument exception if date is invalid
* Use GetDate() to get date formatted as "dd/mm/yyy"
* Use GetAscTime() to get date formatted as "ddd mmm yy hh:mm:ss yyyy"
* Substraction can be done between dates, it will return the differences in days
* i.e. Date today - Date yesterday = 1
* TODO: overload + operator as Date + int
* TODO: overload - operator as Date - int
*/
#include <ctime>
#include <string>
#ifndef DATE_H_
#define DATE_H_
class Date
{
public:
Date();
void Set(int day, int month, int year);
int operator - (const Date& rhs);
const char* GetDate() const;
const char* GetAscTime() const;
time_t GetDateValue() const;
private:
std::time_t ttTime;
std::tm tmTime;
mutable char szTimeBuffer[255];
static constexpr int nSecPerDay = 60 * 60 * 24;
};
#endif /* DATE_H_ */
Date.cpp
/*
* Date.cpp
*/
#include "Date.h"
#include <stdexcept>
Date::Date()
: ttTime(0), tmTime({0}), szTimeBuffer("")
{
std::time(&ttTime);
localtime_s(&tmTime, &ttTime);
}
void Date::Set(int day, int month, int year)
{
tmTime.tm_mday = day;
tmTime.tm_mon = month - 1;
tmTime.tm_year = year - 1900;
ttTime = std::mktime(&tmTime);
// Temp date constructed to check if Feb 29th for the specified year exists
// checks if the value of 29/Feb/YYYY is the same as 01/Mar/YYYY
// if true, means that year is not leap year and should not have Feb 29th
// throws invalid argument exception
std::tm tmTemp = {0};
std::time_t ttTemp = 0;
// Specify march 1st, use same year as input
tmTemp.tm_mday = 1;
tmTemp.tm_mon = month;
tmTemp.tm_year = tmTime.tm_year;
ttTemp = std::mktime(&tmTemp);
if(ttTemp == ttTime)
{
std::string errMsg("Error!, Feb 29th doesn't exist in year ");
errMsg.append(std::to_string(tmTime.tm_year + 1900));
errMsg.append("!!");
throw( std::invalid_argument(errMsg) );
}
}
int Date::operator -(const Date& rhs)
{
return (std::difftime(ttTime, rhs.ttTime) / nSecPerDay);
}
const char* Date::GetDate() const
{
std::strftime(szTimeBuffer, 255, "%d/%m/%y", &tmTime);
return szTimeBuffer;
}
const char* Date::GetAscTime() const
{
asctime_s(szTimeBuffer, 255, &tmTime);
return szTimeBuffer;
}
time_t Date::GetDateValue() const
{
return ttTime;
}
nSecPerDay = 60 * 60 * 24
- but not when there's a leap second! \$\endgroup\$