实现C++实用的时间库

    完整工程代码放在我的github上:https://github.com/yjwwyygy/CrossPlatformLibrary

    根据C库提供的时间函数,实现一个方便实用的时间类。它应该具有以下基本功能:

    (1)方便的获取当前时间/指定时间的年、月、日、时、分、秒以及毫秒值。

    (2)支持时间的简单运算、比较。

    (3)支持时间对象转换为简单格式字符串以及简单字符串转换成时间对象。

    (4)不用特别复杂,功能够用就行,若再有必要的功能,再添加。

    类组成如下:

类名

说明

Time

精确到秒的时间类

TimeSpan

Time做算术运算的结果类

MilliTime

精确到毫秒的时间类

MilliTimeSpan

MilliTime做算术运算的结果类

     类继承关系如下:



    代码如下(以下是已经写好的代码,有点多,可以只关注头文件中类接口的定义):

#ifndef BASE_TIME_H
#define BASE_TIME_H

#include "base_def.h"
#include 
   
   
    
    
#include 
    
    
     
     
#include "err.h"

#ifdef WIN32
#include 
     
     
      
      
#endif

#ifndef WIN32
#include 
      
      
       
       
#endif

// 秒级别的时间差类
class BASE_EXPORT TimeSpan
{
public:
    TimeSpan();
    TimeSpan(time_t time);
    TimeSpan(long nDays, int nHours, int nMins, int nSecs);
    TimeSpan(const TimeSpan& timeSpan);

    const TimeSpan& operator = (const TimeSpan& timeSpan);

    long GetDays() const;
    long GetTotalHours() const;
    long GetTotalMinutes() const;
    long GetTotalSeconds() const;
    int GetHours() const;
    int GetMinutes() const;
    int GetSeconds() const;

	TimeSpan operator + (const TimeSpan& timeSpan) const;
	TimeSpan operator - (const TimeSpan& timeSpan) const;
    const TimeSpan& operator += (const TimeSpan& timeSpan);
    const TimeSpan& operator -= (const TimeSpan& timeSpan);
    bool operator == (const TimeSpan& timeSpan) const;
    bool operator != (const TimeSpan& timeSpan) const;
    bool operator < (const TimeSpan& timeSpan) const;
    bool operator > (const TimeSpan& timeSpan) const;
    bool operator <= (const TimeSpan& timeSpan) const;
    bool operator >= (const TimeSpan& timeSpan) const;

protected:
    time_t m_timeSpan;
    friend class Time;
};

// 秒级别的时间类
class BASE_EXPORT Time
{
public:
    Time();
    Time(time_t tm);
    Time(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec);

    static Time GetCurrentTime();

    bool SetUTCTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec);
    void GetUTCTime(int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec) const;
    void GetLocalTm(struct tm* localtime) const;
    void GetGmTm(struct tm* gm) const;
	std::string ToString() const;
	std::string ToUTCString() const;
	std::string DateToString() const;
	std::string UTCDateToString() const;
	std::string TimeToString() const;
	std::string UTCTimeToString() const;

    time_t GetTime() const;

    int GetUTCYear() const;
    int GetUTCMonth() const;
    int GetUTCDay() const;
    int GetUTCHour() const;
    int GetUTCMinute() const;
    int GetUTCSecond() const;
    int GetUTCDayOfWeek() const;
    int GetUTCDayOfMonth() const;
    int GetUTCDayOfYear() const;

    int GetYear() const;
    int GetMonth() const;
    int GetDay() const;
    int GetHour() const;
    int GetMinute() const;
    int GetSecond() const;
    int GetDayOfWeek() const;
    int GetDayOfMonth() const;
    int GetDayOfYear() const;

    TimeSpan operator - (const Time& time) const;
    Time operator - (const TimeSpan& time) const;
    Time operator + (const TimeSpan& timeSpan) const;
    const Time& operator += (const TimeSpan& timeSpan);
    const Time& operator -= (const TimeSpan& timeSpan);
    bool operator == (const Time& time) const;
    bool operator != (const Time& time) const;
    bool operator < (const Time& time) const;
    bool operator > (const Time& time) const;
    bool operator <= (const Time& time) const;
    bool operator >= (const Time& time) const;

protected:
    time_t m_time;
};

// 毫秒级别的时间差类
class BASE_EXPORT MilliTimeSpan : public TimeSpan
{
public:
	MilliTimeSpan();
	MilliTimeSpan(time_t time, int nMins);
	MilliTimeSpan(long lDays, int nHours, int nMins, int nSecs, int nMills);

	MilliTimeSpan(const MilliTimeSpan& timeSpanSrc);
	const MilliTimeSpan& operator=(const MilliTimeSpan& timeSpanSrc);

	int GetMillisecond() const { return m_nMilli; }

	MilliTimeSpan operator-(const MilliTimeSpan& timeSpan) const;
	MilliTimeSpan operator+(const MilliTimeSpan& timeSpan) const;
	const MilliTimeSpan& operator+=(const MilliTimeSpan& timeSpan);
	const MilliTimeSpan& operator-=(const MilliTimeSpan& timeSpan);
	bool operator==(const MilliTimeSpan& timeSpan) const;
	bool operator!=(const MilliTimeSpan& timeSpan) const;
	bool operator<(const MilliTimeSpan& timeSpan) const;
	bool operator>(const MilliTimeSpan& timeSpan) const;
	bool operator<=(const MilliTimeSpan& timeSpan) const;
	bool operator>=(const MilliTimeSpan& timeSpan) const;

protected:
	int m_nMilli;    // 毫秒值
	friend class MilliTime;
};

// 毫秒级别的时间类
class BASE_EXPORT MilliTime : public Time
{
public:
	MilliTime();
	MilliTime(time_t tm, int nMills);

	MilliTime(Time& t) : Time(t), m_nMilli(0)    {}
	MilliTime(const char * str)    { SetLocalByStringA(str); }
	MilliTime(const wchar_t* str)    { SetLocalByStringW(str); }

	MilliTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nMilli);
	MilliTime(const MilliTime& right);

public:
	void SetMillisecond(int nMilli) { m_nMilli = nMilli; }
	int GetMillisecond() const { return m_nMilli; }
	void SetUTCByStringA(const char * str);
	void SetUTCByStringW(const wchar_t* str);
	void SetLocalByStringA(const char * str);
	void SetLocalByStringW(const wchar_t* str);
	std::string ToStringA();
	std::wstring ToStringW();
	std::string ToUTCStringA();
	std::wstring ToUTCStringW();
	static bool ParseStrW(const wchar_t* str, int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec, int &nMilli);
	static bool ParseStrA(const char * str, int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec, int &nMilli);

public:
	MilliTimeSpan operator-(const MilliTime& time) const;
	MilliTime operator-(const MilliTimeSpan& timeSpan) const;
	MilliTime operator+(const MilliTimeSpan& timeSpan) const;
	const MilliTime& operator+=(const MilliTimeSpan& timeSpan);
	const MilliTime& operator-=(const MilliTimeSpan& timeSpan);
	bool operator==(const MilliTime& time) const;
	bool operator!=(const MilliTime& time) const;
	bool operator<(const MilliTime& time) const;
	bool operator>(const MilliTime& time) const;
	bool operator<=(const MilliTime& time) const;
	bool operator>=(const MilliTime& time) const;

protected:
	int m_nMilli; // 毫秒值
};

/************************************************************************/
/* TimeSpan内联定义 */
/************************************************************************/
inline TimeSpan::TimeSpan()
{
}

inline TimeSpan::TimeSpan(time_t time)
{
    m_timeSpan = time; 
}

inline TimeSpan::TimeSpan(long lDays, int nHours, int nMins, int nSecs)
{
    m_timeSpan = nSecs + 60* (nMins + 60* (nHours + 24* lDays)); 
}

inline TimeSpan::TimeSpan(const TimeSpan& timeSpanSrc)
{
    m_timeSpan = timeSpanSrc.m_timeSpan; 
}

inline const TimeSpan& TimeSpan::operator=(const TimeSpan& timeSpanSrc)
{
    m_timeSpan = timeSpanSrc.m_timeSpan; 
    return *this; 
}

inline long TimeSpan::GetDays() const
{
    return (long)m_timeSpan / (24 * 3600L); 
}

inline long TimeSpan::GetTotalHours() const
{
    return (long)m_timeSpan/3600; 
}

inline int TimeSpan::GetHours() const
{
    return (int)(GetTotalHours() - GetDays() * 24); 
}

inline long TimeSpan::GetTotalMinutes() const
{
    return (long)m_timeSpan / 60; 
}

inline int TimeSpan::GetMinutes() const
{
    return (int)(GetTotalMinutes() - GetTotalHours() * 60); 
}

inline long TimeSpan::GetTotalSeconds() const
{
    return (long)m_timeSpan; 
}

inline int TimeSpan::GetSeconds() const
{
    return (int)(GetTotalSeconds() - GetTotalMinutes() * 60); 
}

inline TimeSpan TimeSpan::operator + (const TimeSpan& timeSpan) const
{
	return TimeSpan(m_timeSpan + timeSpan.m_timeSpan);
}

inline TimeSpan TimeSpan::operator - (const TimeSpan& timeSpan) const
{
    return TimeSpan(m_timeSpan - timeSpan.m_timeSpan); 
}

inline const TimeSpan& TimeSpan::operator += (const TimeSpan& timeSpan)
{
    m_timeSpan += timeSpan.m_timeSpan; 
    return *this; 
}

inline const TimeSpan& TimeSpan::operator -= (const TimeSpan& timeSpan)
{
    m_timeSpan -= timeSpan.m_timeSpan; 
    return *this; 
}

inline bool TimeSpan::operator == (const TimeSpan& timeSpan) const
{
    return m_timeSpan == timeSpan.m_timeSpan; 
}

inline bool TimeSpan::operator != (const TimeSpan& timeSpan) const
{
    return m_timeSpan != timeSpan.m_timeSpan; 
}

inline bool TimeSpan::operator < (const TimeSpan& timeSpan) const
{
    return m_timeSpan < timeSpan.m_timeSpan;
}

inline bool TimeSpan::operator > (const TimeSpan& timeSpan) const
{
    return m_timeSpan > timeSpan.m_timeSpan; 
}

inline bool TimeSpan::operator <= (const TimeSpan& timeSpan) const
{
    return m_timeSpan <= timeSpan.m_timeSpan; 
}

inline bool TimeSpan::operator >= (const TimeSpan& timeSpan) const
{
    return m_timeSpan >= timeSpan.m_timeSpan; 
}

/************************************************************************/
/* Time内联定义 */
/************************************************************************/
inline time_t Time::GetTime() const
{
    return m_time; 
}

inline int Time::GetYear() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_year + 1900; 
}

inline int Time::GetMonth() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_mon + 1;
}

inline int Time::GetDay() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif 
	return t.tm_mday; 
}

inline int Time::GetHour() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_hour; 
}

inline int Time::GetMinute() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif 
	return t.tm_min; 
}

inline int Time::GetSecond() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_sec; 
}

inline int Time::GetDayOfWeek() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_wday + 1;
}

inline int Time::GetDayOfMonth() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_mday;
}

inline int Time::GetDayOfYear() const
{
	tm t;
#ifdef WIN32
    localtime_s(&t, &m_time);
#else
	localtime_r(&m_time, &t);
#endif
	return t.tm_yday + 1;
}

inline int Time::GetUTCYear() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_year + 1900;
}

inline int Time::GetUTCMonth() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_mon + 1;
}

inline int Time::GetUTCDay() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_mday; 
}

inline int Time::GetUTCHour() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_hour; 
}

inline int Time::GetUTCMinute() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_min; 
}

inline int Time::GetUTCSecond() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_sec; 
}

inline int Time::GetUTCDayOfWeek() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_wday + 1; 
}

inline int Time::GetUTCDayOfMonth() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_mday; 
}

inline int Time::GetUTCDayOfYear() const
{
	tm t;
#ifdef WIN32
    gmtime_s(&t, &m_time);
#else
	gmtime_r(&m_time, &t);
#endif
	return t.tm_yday + 1; 
}

inline TimeSpan Time::operator - (const Time& time) const
{
    return TimeSpan(m_time - time.m_time); 
}

inline Time Time::operator - (const TimeSpan& timeSpan) const
{
    return Time(m_time - timeSpan.m_timeSpan); 
}

inline Time Time::operator + (const TimeSpan& timeSpan) const
{
    return Time(m_time + timeSpan.m_timeSpan); 
}

inline const Time& Time::operator += (const TimeSpan& timeSpan)
{
    m_time += timeSpan.m_timeSpan; 
    return *this; 
}

inline const Time& Time::operator -= (const TimeSpan& timeSpan)
{
    m_time -= timeSpan.m_timeSpan; 
    return *this; 
}

inline bool Time::operator==(const Time& time) const
{
    return m_time == time.m_time; 
}

inline bool Time::operator!=(const Time& time) const
{
    return m_time != time.m_time; 
}

inline bool Time::operator<(const Time& time) const
{
    return m_time < time.m_time; 
}

inline bool Time::operator>(const Time& time) const
{
    return m_time > time.m_time; 
}

inline bool Time::operator<=(const Time& time) const
{
    return m_time <= time.m_time; 
}

inline bool Time::operator>=(const Time& time) const
{
    return m_time >= time.m_time; 
}

/************************************************************************/
/* MilliTimeSpan内联定义 */
/************************************************************************/
inline MilliTimeSpan::MilliTimeSpan() : m_nMilli(0)
{

}

inline MilliTimeSpan::MilliTimeSpan(time_t time, int nMilli) : TimeSpan(time)
{
	BASE_ASSERT(nMilli >= 0 && nMilli < 1000);
	m_nMilli = nMilli;
}

inline MilliTimeSpan::MilliTimeSpan(long lDays, int nHours, int nMins, int nSecs, int nMilli)
	: TimeSpan(lDays, nHours, nMins, nSecs)
{
	BASE_ASSERT(nMilli >= 0 && nMilli < 1000);
	m_nMilli = nMilli;
}

inline MilliTimeSpan::MilliTimeSpan(const MilliTimeSpan& timeSpanSrc)
	: TimeSpan(timeSpanSrc), m_nMilli(timeSpanSrc.m_nMilli)
{

}

inline const MilliTimeSpan& MilliTimeSpan::operator=(const MilliTimeSpan& timeSpanSrc)
{
	m_timeSpan = timeSpanSrc.m_timeSpan;
	m_nMilli = timeSpanSrc.m_nMilli;
	return *this;
}

inline MilliTimeSpan MilliTimeSpan::operator-(const MilliTimeSpan& timeSpan) const
{
	if (m_nMilli < timeSpan.m_nMilli)
	{
		return MilliTimeSpan(m_timeSpan - timeSpan.m_timeSpan - 1, m_nMilli - timeSpan.m_nMilli + 1000);
	}
	else
	{
		return MilliTimeSpan(m_timeSpan - timeSpan.m_timeSpan, m_nMilli - timeSpan.m_nMilli);
	}
}

inline const MilliTimeSpan& MilliTimeSpan::operator-=(const MilliTimeSpan& timeSpan)
{
	if (m_nMilli < timeSpan.m_nMilli)
	{
		m_timeSpan -= (timeSpan.m_timeSpan + 1), m_nMilli -= (timeSpan.m_nMilli - 1000);
	}
	else
	{
		m_timeSpan -= timeSpan.m_timeSpan, m_nMilli -= timeSpan.m_nMilli;
	}

	return *this;
}

inline MilliTimeSpan MilliTimeSpan::operator+(const MilliTimeSpan& timeSpan) const
{
	int nMilli = m_nMilli + timeSpan.m_nMilli;
	if (nMilli >= 1000)
	{
		return MilliTimeSpan(m_timeSpan + timeSpan.m_timeSpan + 1, nMilli - 1000);
	}
	else
	{
		return MilliTimeSpan(m_timeSpan + timeSpan.m_timeSpan, nMilli);
	}
}

inline const MilliTimeSpan& MilliTimeSpan::operator+=(const MilliTimeSpan& timeSpan)
{
	int nMilli = m_nMilli + timeSpan.m_nMilli;
	if (nMilli >= 1000)
	{
		m_timeSpan += (timeSpan.m_timeSpan + 1), m_nMilli = (nMilli - 1000);
	}
	else
	{
		m_timeSpan += timeSpan.m_timeSpan, m_nMilli = nMilli;
	}

	return *this;
}

inline bool MilliTimeSpan::operator==(const MilliTimeSpan& timeSpan) const
{
	return m_timeSpan == timeSpan.m_timeSpan && m_nMilli == timeSpan.m_nMilli;
}

inline bool MilliTimeSpan::operator!=(const MilliTimeSpan& timeSpan) const
{
	return m_timeSpan != timeSpan.m_timeSpan || m_nMilli != timeSpan.m_nMilli;
}

inline bool MilliTimeSpan::operator<(const MilliTimeSpan& timeSpan) const
{
	return (m_timeSpan == timeSpan.m_timeSpan) ? (m_nMilli < timeSpan.m_nMilli) : (m_timeSpan < timeSpan.m_timeSpan);
}

inline bool MilliTimeSpan::operator>(const MilliTimeSpan& timeSpan) const
{
	return (m_timeSpan == timeSpan.m_timeSpan) ? (m_nMilli > timeSpan.m_nMilli) : (m_timeSpan > timeSpan.m_timeSpan);
}

inline bool MilliTimeSpan::operator<=(const MilliTimeSpan& timeSpan) const
{
	return (m_timeSpan == timeSpan.m_timeSpan) ? (m_nMilli <= timeSpan.m_nMilli) : (m_timeSpan <= timeSpan.m_timeSpan);
}

inline bool MilliTimeSpan::operator>=(const MilliTimeSpan& timeSpan) const
{
	return (m_timeSpan == timeSpan.m_timeSpan) ? (m_nMilli >= timeSpan.m_nMilli) : (m_timeSpan >= timeSpan.m_timeSpan);
}

/************************************************************************/
/* MilliTime内联定义 */
/************************************************************************/
inline MilliTime::MilliTime()
{
#ifdef WIN32
	SYSTEMTIME   st;
	GetLocalTime(&st);
	m_nMilli = st.wMilliseconds;
#else
	struct timeval nowtimeval;
	gettimeofday(&nowtimeval, 0);
	m_nMilli = nowtimeval.tv_usec / 1000;
	//m_time = nowtimeval.tv_sec;
#endif
}

inline MilliTime::MilliTime(time_t tm, int nMills) : Time(tm), m_nMilli(nMills)
{
	BASE_ASSERT(m_nMilli >= 0 && m_nMilli < 1000);
}

inline MilliTime::MilliTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nMilli)
	: Time(nYear, nMonth, nDay, nHour, nMin, nSec)
{
	BASE_ASSERT(nMilli >= 0 && nMilli < 1000);
	m_nMilli = nMilli;
}

inline MilliTime::MilliTime(const MilliTime& right) : Time(right), m_nMilli(right.m_nMilli)
{

}

inline MilliTimeSpan MilliTime::operator-(const MilliTime& right) const
{
	if (m_nMilli < right.m_nMilli)
	{
		return MilliTimeSpan(m_time - right.m_time - 1, m_nMilli - right.m_nMilli + 1000);
	}
	else
	{
		return MilliTimeSpan(m_time - right.m_time, m_nMilli - right.m_nMilli);
	}
}

inline MilliTime MilliTime::operator-(const MilliTimeSpan& right) const
{
	if (m_nMilli < right.m_nMilli)
	{
		return MilliTime(m_time - right.m_timeSpan - 1, m_nMilli - right.m_nMilli + 1000);
	}
	else
	{
		return MilliTime(m_time - right.m_timeSpan, m_nMilli - right.m_nMilli);
	}
}

inline const MilliTime& MilliTime::operator-=(const MilliTimeSpan& timeSpan)
{
	if (m_nMilli < timeSpan.m_nMilli)
	{
		m_time -= timeSpan.m_timeSpan - 1, m_nMilli -= (timeSpan.m_nMilli - 1000);
	}
	else
	{
		m_time -= timeSpan.m_timeSpan, m_nMilli -= timeSpan.m_nMilli;
	}

	return *this;
}

inline MilliTime MilliTime::operator+(const MilliTimeSpan& timeSpan) const
{
	if ((m_nMilli + timeSpan.m_nMilli) >= 1000)
	{
		return MilliTime(m_time + timeSpan.m_timeSpan + 1, m_nMilli + timeSpan.m_nMilli - 1000);
	}
	else
	{
		return MilliTime(m_time + timeSpan.m_timeSpan, m_nMilli + timeSpan.m_nMilli);
	}
}

inline const MilliTime& MilliTime::operator+=(const MilliTimeSpan &timeSpan)
{
	if ((m_nMilli + timeSpan.m_nMilli) >= 1000)
	{
		m_time += (timeSpan.m_timeSpan + 1), m_nMilli += (timeSpan.m_nMilli - 1000);
	}
	else
	{
		m_time += timeSpan.m_timeSpan, m_nMilli += timeSpan.m_nMilli;
	}

	return *this;
}

inline bool MilliTime::operator==(const MilliTime& time) const
{
	return (m_time == time.m_time) && (m_nMilli == time.m_nMilli);
}

inline bool MilliTime::operator!=(const MilliTime& time) const
{
	return (m_time != time.m_time) || (m_nMilli != time.m_nMilli);
}

inline bool MilliTime::operator<(const MilliTime& time) const
{
	return (m_time == time.m_time) ? (m_nMilli < time.m_nMilli) : (m_time < time.m_time);
}

inline bool MilliTime::operator>(const MilliTime& time) const
{
	return (m_time == time.m_time) ? (m_nMilli > time.m_nMilli) : (m_time > time.m_time);
}

inline bool MilliTime::operator<=(const MilliTime& time) const
{
	return (m_time == time.m_time) ? (m_nMilli <= time.m_nMilli) : (m_time <= time.m_time);
}

inline bool MilliTime::operator>=(const MilliTime& time) const
{
	return (m_time == time.m_time) ? (m_nMilli >= time.m_nMilli) : (m_time >= time.m_time);
}

extern wchar_t* my_wcstok(wchar_t *wcs, const wchar_t *delim);
extern char* my_strtok(char *wcs, const char *delim);

#endif
      
      
     
     
    
    
   
   
#include "base_time.h"
#include "except.h"
#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      

using namespace std;

#define _MAX__TIME64_T     0x793406fffLL 

// 参考Linux源代码中的实现
// 详解访问:http://blog.csdn.net/axx1611/article/details/1792827
static inline unsigned long linux_mktime (
              unsigned int year, unsigned int mon,
              unsigned int day, unsigned int hour,
              unsigned int min, unsigned int sec)
{
    /* 1..12 -> 11,12,1..10 */
    if (0 >= (int) (mon -= 2)) 
    {    
        mon += 12;        /* Puts Feb last since it has leap day */
        year -= 1;
    }

    return ((((unsigned long) (year / 4 - year / 100 + year / 400 + 367 * mon / 12 + day)
              + year * 365 - 719499) * 24 + hour) * 60 + min ) * 60 + sec; /* finally seconds */
}


/************************************************************************/
/* Time定义 */
/************************************************************************/
Time::Time()
{
    m_time = time(NULL);
}

Time::Time(time_t tm)
{
    m_time = tm;
}

Time::Time(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec)
{
    if (SetUTCTime (nYear, nMonth, nDay, nHour, nMin, nSec))
    {
#ifdef WIN32
        _tzset ();
        long timezone;
        _get_timezone(&timezone);
        m_time += timezone;
#else
        tzset ();
        m_time += timezone;        
#endif
    }
}

bool Time::SetUTCTime (int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec)
{
    if ((nDay >= 1 && nDay <= 31)
        && (nMonth >= 1 && nMonth <= 12)
        && (nYear >= 1900)
		&& (nHour >= 0 && nHour <= 23)
		&& (nMin >= 0 && nMin <= 59)
		&& (nSec >= 0 && nSec <= 59))
    {
        m_time = linux_mktime (nYear, nMonth, nDay, nHour, nMin, nSec);
        return true;
    }

    m_time = -1;

    return false;
}

void Time::GetLocalTm(struct tm* lc) const
{
#ifdef WIN32
    localtime_s(lc, &m_time);
#else
	localtime_r(&m_time, lc);
#endif
}

void Time::GetGmTm (struct tm* gm) const
{
#ifdef WIN32
    gmtime_s(gm, &m_time);
#else
	gmtime_r(&m_time, gm);
#endif
}

void Time::GetUTCTime (int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec) const
{
    if (m_time > 0 && m_time <= _MAX__TIME64_T)
    {
        struct tm g;
        GetGmTm(&g);

        nYear = g.tm_year + 1900;
        nMonth = g.tm_mon + 1;
        nDay = g.tm_mday;
        nHour = g.tm_hour;
        nMin = g.tm_min;
        nSec = g.tm_sec;
    }
}

Time Time::GetCurrentTime ()
{
    return Time(time(NULL));
}

string Time::ToString() const
{
    char szTime[100] = {0};
    if (m_time > 0 && m_time <= _MAX__TIME64_T )
    {
#ifdef WIN32
        sprintf_s(szTime, 100, "%4d-%02d-%02d %02d:%02d:%02d",
            GetYear(), GetMonth(), GetDay(),
            GetHour(), GetMinute(), GetSecond());
#else
        sprintf(szTime, "%4d-%02d-%02d %02d:%02d:%02d",
            GetYear(), GetMonth(), GetDay(),
            GetHour(), GetMinute(), GetSecond());
#endif
    }
    return string(szTime);
}

string Time::ToUTCString() const
{
    char szTime[100] = {0};
    if (m_time > 0 && m_time <= _MAX__TIME64_T )
    {
#ifdef WIN32
        sprintf_s(szTime, 100, "%4d-%02d-%02d %02d:%02d:%02d",
            GetUTCYear(), GetUTCMonth(), GetUTCDay(),
            GetUTCHour(), GetUTCMinute(), GetUTCSecond());
#else
        sprintf(szTime, "%4d-%02d-%02d %02d:%02d:%02d",
            GetUTCYear(), GetUTCMonth(), GetUTCDay(),
            GetUTCHour(), GetUTCMinute(), GetUTCSecond());
#endif
    }
    return string(szTime);
}

string Time::DateToString() const
{
	char szTime[100] = { 0 };
	if (m_time > 0 && m_time <= _MAX__TIME64_T)
	{
#ifdef WIN32
		sprintf_s(szTime, 100, "%4d%02d%02d", GetYear(), GetMonth(), GetDay());
#else
		sprintf(szTime, "%4d%02d%02d", GetYear(), GetMonth(), GetDay());
#endif
	}

	return string(szTime);
}

string Time::UTCDateToString() const
{
	char szTime[100] = {0};
	if (m_time > 0 && m_time <= _MAX__TIME64_T )
	{
#ifdef WIN32
		sprintf_s(szTime, 100, "%4d%02d%02d", GetUTCYear(), GetUTCMonth(), GetUTCDay());
#else
		sprintf(szTime, "%4d%02d%02d",	GetUTCYear(), GetUTCMonth(), GetUTCDay());
#endif
	}

	return string(szTime);
}

string Time::TimeToString() const
{
 	char szTime[100] = {0};
 	if (m_time > 0 && m_time <= _MAX__TIME64_T )
 	{
#ifdef WIN32
 		sprintf_s(szTime, 100, "%02d%02d%02d", GetHour(), GetMinute(), GetSecond());
#else
 		sprintf(szTime, "%02d%02d%02d",	GetHour(), GetMinute(), GetSecond());
#endif
 	}

	return string(szTime);
}

string Time::UTCTimeToString() const
{
	char szTime[100] = { 0 };
	if (m_time > 0 && m_time <= _MAX__TIME64_T)
	{
#ifdef WIN32
		sprintf_s(szTime, 100, "%02d%02d%02d", GetUTCHour(), GetUTCMinute(), GetUTCSecond());
#else
		sprintf(szTime, "%02d%02d%02d", GetUTCHour(), GetUTCMinute(), GetUTCSecond());
#endif
	}

	return string(szTime);
}

/************************************************************************/
/* MilliTime定义 */
/************************************************************************/
std::string MilliTime::ToStringA ()
{
    char szTime[100] = {0};
    if (m_time > 0 && m_time <= _MAX__TIME64_T)
    {
#ifdef WIN32
        sprintf_s(szTime, 100, "%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetYear(), GetMonth(), GetDay(),
            GetHour(), GetMinute(), GetSecond(), GetMillisecond());
#else
        sprintf(szTime, "%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetYear(), GetMonth(), GetDay(),
            GetHour(), GetMinute(), GetSecond(), GetMillisecond());
#endif
    }

    return string(szTime);
}

std::wstring MilliTime::ToStringW ()
{
    wchar_t buf[30];
    if (m_time > 0 && m_time <= _MAX__TIME64_T )
    {
        swprintf(buf,30, L"%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetYear(), GetMonth(), GetDay(),
            GetHour(), GetMinute(), GetSecond(), GetMillisecond());
    }
    return buf;
}

std::string MilliTime::ToUTCStringA()
{
    char szTime[100] = {0};
    if (m_time > 0 && m_time <= _MAX__TIME64_T)
    {
#ifdef WIN32
        sprintf_s(szTime, 100, "%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetUTCYear(), GetUTCMonth(), GetUTCDay(),
            GetUTCHour(), GetUTCMinute(), GetUTCSecond(), GetMillisecond());
#else
        sprintf(szTime, "%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetUTCYear(), GetUTCMonth(), GetUTCDay(),
            GetUTCHour(), GetUTCMinute(), GetUTCSecond(), GetMillisecond());
#endif
    }

    return string(szTime);
}

std::wstring MilliTime::ToUTCStringW()
{
    wchar_t buf[30];
    if (m_time > 0 && m_time <= _MAX__TIME64_T )
    {
        swprintf(buf,30, L"%04d-%02d-%02d %02d:%02d:%02d.%03d", 
            GetUTCYear(), GetUTCMonth(), GetUTCDay(),
            GetUTCHour(), GetUTCMinute(), GetUTCSecond(), GetMillisecond());
    }
    return buf;
}

#ifdef WIN32
// 自定义字符拆分函数
wchar_t* my_wcstok(wchar_t *wcs, const wchar_t *delim)
{
    static wchar_t *state = NULL;
    return wcstok_s(wcs, delim, &state);
}

char* my_strtok(char* cs, const char* delim)
{
    static char* state = NULL;
    return strtok_s(cs, delim, &state);
}
#else
long _wtoi(const wchar_t *ptr)
{
    wchar_t *end_ptr = NULL;
    return wcstol(ptr, &end_ptr, 10);
}

wchar_t *my_wcstok(wchar_t *wcs, const wchar_t *delim)
{
    static wchar_t *state = NULL;
    return wcstok (wcs, delim, &state);
}

char* my_strtok(char* cs, const char* delim)
{
	static char *state = NULL;
    return strtok_r(cs, delim, &state);
}
#endif // WIN32

bool MilliTime::ParseStrW (const wchar_t* str_in, int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec, int &nMilli)
{
    wstring str(str_in);
    wchar_t seps1[]   = L"-/";
    wchar_t seps2[]   = L" ";
    wchar_t seps3[]   = L":";
    wchar_t seps4[]   = L".";

    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    bool ok = false;
    wchar_t* tok = my_wcstok ((wchar_t *)str.c_str(), seps1);    // take year
    if (NULL != tok)
    {
        year = _wtoi(tok);
        tok = my_wcstok (NULL, seps1);    // take month
        if (NULL != tok)
        {
            mon = _wtoi (tok);
            tok = my_wcstok (NULL, seps2);    // take day
            if (NULL != tok)
            {
                day = _wtoi(tok);
                ok = true;
                tok = my_wcstok(NULL, seps3);    // take hour
                if (NULL != tok)
                {
                    ok = false;
                    hour = _wtoi(tok);
                    tok = my_wcstok(NULL, seps3);    // take min
                    if (NULL != tok)
                    {
                        min = _wtoi(tok);
                        tok = my_wcstok(NULL, seps4);    // take second
                        if (NULL != tok)
                        {
                            sec = _wtoi(tok);
                            ok = true;
                            tok = my_wcstok(NULL, seps4);    // take milli
                            if (NULL != tok)
                                milli = _wtoi(tok);
                        }
                    }
                }
            }
        }
    }

    if (ok)
    {
        nYear = year;
        nMonth = mon;
        nDay = day;
        nHour = hour;
        nMin = min;
        nSec = sec;
        nMilli = milli;
        return true;
    }

    return false;
}


bool MilliTime::ParseStrA (const char * str_in, int &nYear, int &nMonth, int &nDay, int &nHour, int &nMin, int &nSec, int &nMilli)
{
    string str(str_in);
    char seps1[]   = "-/";
    char seps2[]   = " ";
    char seps3[]   = ":";
    char seps4[]   = ".";

    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    bool ok = false;

    const char* tok = my_strtok ((char *)str.c_str(), seps1);    // take year
    if (NULL != tok)
    {
        year = atoi(tok);
        tok = my_strtok (NULL, seps1);    // take month
        if (NULL != tok)
        {
            mon = atoi (tok);
            tok = my_strtok (NULL, seps2);    // take day
            if (NULL != tok)
            {
                day = atoi(tok);
                ok = true;
                tok = my_strtok(NULL, seps3);    // take hour
                if (NULL != tok)
                {
                    ok = false;
                    hour = atoi(tok);
                    tok = my_strtok(NULL, seps3);    // take min
                    if (NULL != tok)
                    {
                        min = atoi(tok);
                        tok = my_strtok(NULL, seps4);    // take second
                        if (NULL != tok)
                        {
                            sec = atoi(tok);
                            ok = true;
                            tok = my_strtok(NULL, seps4);    // take milli
                            if (NULL != tok)
                                milli = atoi(tok);
                        }
                    }
                }
            }
        }
    }

    if (ok)
    {
        nYear = year;
        nMonth = mon;
        nDay = day;
        nHour = hour;
        nMin = min;
        nSec = sec;
        nMilli = milli;
        return true;
    }

    return false;
}

void MilliTime::SetUTCByStringW (const wchar_t* str)
{
    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    if (ParseStrW(str, year, mon, day, hour, min, sec, milli))
    {
        SetUTCTime(year, mon, day, hour, min, sec);
        m_nMilli = milli;
    }
    else
    {
        throw Except (DATETIME_FMT, "Datetime format error. used as yyyy-mm-dd HH:MM:SS.xxxx");
    }
}
                
void MilliTime::SetLocalByStringW (const wchar_t* str)
{
    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    if (ParseStrW(str, year, mon, day, hour, min, sec, milli))
    {
        m_time = Time(year, mon, day, hour, min, sec).GetTime();
        m_nMilli = milli;
    }
    else
    {
        throw Except (DATETIME_FMT, "Datetime format error. used as yyyy-mm-dd HH:MM:SS.xxxx");
    }
}

void MilliTime::SetUTCByStringA(const char * str)
{
    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    if (ParseStrA(str, year, mon, day, hour, min, sec, milli))
    {
        SetUTCTime(year, mon, day, hour, min, sec);
        m_nMilli = milli;
    }
	else
	{
		throw Except (DATETIME_FMT, "Datetime format error. used as yyyy-mm-dd HH:MM:SS.xxxx");
	}
}

void MilliTime::SetLocalByStringA(const char * str)
{
    int year = 0, mon = 0, day = 0, hour = 0, min = 0, sec = 0, milli = 0;
    if (ParseStrA(str, year, mon, day, hour, min, sec, milli))
    {
        m_time = Time(year, mon, day, hour, min, sec).GetTime();
        m_nMilli = milli;
    }
	else
	{
		throw Except (DATETIME_FMT, "Datetime format error. used as yyyy-mm-dd HH:MM:SS.xxxx");
	}
}
     
     
    
    
   
   

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值