I don't think there is one 'proper' way
Aim for an interface which is complete and minimal.
You're in luck, I was screwing around the other night and I made this:
Code:
class Time
{
public:
// Array of 3 letter abbreviations for each day name
static const std::string days[];
// Array of 3 letter abbreviations for each month name
static const std::string months[];
public:
// Default constructor and destructor
Time();
Time(const tm* rhs) { copytmlocal(rhs); }
~Time() {};
// Copy constructors for struct tm and class time
Time(const Time& rhs)
{ m_timestruct = rhs.m_timestruct; }
Time(const ::tm& rhs)
{ m_timestruct = rhs; }
// Assignment operators for struct tm and class time
Time& operator=(const Time& rhs)
{ m_timestruct = rhs.m_timestruct; }
Time& operator=(const ::tm& rhs)
{ m_timestruct = rhs; }
public:
// Equivalent to asctime() in time.h
std::string strtime() const;
// Equivalent to members of the tm structure, only a much nicer interface
inline int day() const { return m_timestruct.tm_wday; }
inline int month() const { return m_timestruct.tm_mon; }
inline int year() const { return m_timestruct.tm_year + 1900; }
inline int minute() const { return m_timestruct.tm_min; }
inline int hour() const { return m_timestruct.tm_hour; }
inline int second() const { return m_timestruct.tm_sec; }
// Equivalent to time(NULL)
inline time_t ticks() const { return ::time(NULL); }
// Creates a tm struct from count and copies it to m_timestruct
inline void ticks(time_t count) { copytmlocal(::localtime(&count)); }
inline Time& localtime();
inline Time& gmtime();
protected:
// Copies a tm structure to m_timestruct using memcpy
inline void copytmlocal(const tm* copy)
{
::memcpy(reinterpret_cast<void*>(&m_timestruct),
reinterpret_cast<const void*>(copy), sizeof(::tm));
}
::tm m_timestruct;
};
const std::string Time::days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
const std::string Time::months[] = { "Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
};
Time::Time()
{
time_t raw = ::time(NULL);
::tm* current = ::localtime(&raw);
copytmlocal(current);
}
inline Time& Time::localtime()
{
time_t now = time(NULL);
copytmlocal(::localtime(&now));
return *this;
}
inline Time& Time::gmtime()
{
time_t now = time(NULL);
copytmlocal(::gmtime(&now));
return *this;
}
std::string Time::strtime() const
{
std::stringstream format;
format << days[m_timestruct.tm_wday] << ' '
<< months[m_timestruct.tm_mon]<< ' 'z
<< m_timestruct.tm_mday << ' '
<< std::setfill('0') << std::setw(2)
<< m_timestruct.tm_hour << ':'
<< std::setfill('0') << std::setw(2)
<< m_timestruct.tm_min << ':'
<< std::setfill('0') << std::setw(2)
<< m_timestruct.tm_sec << ' '
<< 1900 + m_timestruct.tm_year << std::endl;
return format.str();
}
std::ostream& operator<<(std::ostream& out, const Time& print)
{
out << print.strtime();
return out;
}