封装CTime类CMyTime

来源:互联网 发布:什么是大数据开发 编辑:程序博客网 时间:2024/05/21 18:46

CMyTime.h//

#pragma once
class CMyTime
{
    time_t my_time;
public:
    static CMyTime GetCurrentTime();
    CMyTime() { my_time = 0; }
    CMyTime(time_t time)
    {
        my_time = time;
    }
    CMyTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST = -1);
    time_t GetTime() const
    {
        return my_time;
    }
    int GetYear() const;
    int GetMonth() const;
    int GetDay() const;
    int GetHour() const;
    int GetMinute() const;
    int GetSecond() const;
    int GetDayOfWeek() const;
    BOOL operator==(CMyTime time) const
    {
        return this->my_time == time.my_time;
    }
    BOOL operator!=(CMyTime time) const
    {
        return this->my_time != time.my_time;

    }
    BOOL operator<(CMyTime time) const
    {
        return this->my_time < time.my_time;
    }
    BOOL operator>(CMyTime time) const {
        return this->my_time > time.my_time;
    }
    BOOL operator<=(CMyTime time) const
    {
        return this->my_time <= time.my_time;
    }
    BOOL operator>=(CMyTime time) const
    {
        return this->my_time >= time.my_time;
    }
};

CMyTime.cpp//

#include "stdafx.h"
#include "MyTime.h"

CMyTime CMyTime::GetCurrentTime()
{
    return time(NULL);
}
CMyTime::CMyTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST)
{
    tm timo = { nSec,nMin,nHour,nDay,nMonth-1,nYear-1900 };
    my_time = mktime(&timo);
}

int CMyTime::GetYear() const
{
        tm timo;
        localtime_s(&timo, &my_time);
        return timo.tm_year + 1900;
}

int CMyTime::GetMonth() const
{
        tm timo;
        localtime_s(&timo, &my_time);
        return timo.tm_mon + 1;
}

int CMyTime::GetDay() const
{
    tm timo;
    localtime_s(&timo, &my_time);
    return timo.tm_mday;
}

int CMyTime::GetHour() const
{
    tm timo;
    localtime_s(&timo, &my_time);
    return timo.tm_hour;
}

int CMyTime::GetMinute() const
{
    tm timo;
    localtime_s(&timo, &my_time);
    return timo.tm_min;
}

int CMyTime::GetSecond() const
{
        tm timo;
        localtime_s(&timo, &my_time);
        return timo.tm_sec;
}

int CMyTime::GetDayOfWeek() const
{
    tm timo;
    localtime_s(&timo, &my_time);
    return timo.tm_wday + 1;
}