CSystemTime.h
/*
* CSystemTime.h
*
* Created on: 2014-3-12
* Author: qinyinghao
* 用于获取和设置系统时间
*/
#ifndef CSYSTEMTIME_H_
#define CSYSTEMTIME_H_
extern "C" {
#include <time.h>
#include <sys/time.h>
}
namespace qyh {
typedef struct {
int year;
int month;
int day;
int hour;
int minute;
int second;
} TIME;
class CSystemTime {
public:
CSystemTime();
virtual ~CSystemTime();
/*
* 设置系统时间(当地时间)
* 需要管理员权限才能成功设置
* 设置失败返回false
* 设置成功返回true
*/
bool setSystemTime(TIME *_time);
/*
* 获取系统国际标准时间
*/
TIME* getSystemUTCTime();
/*
* 获取系统当地时间
*/
TIME* getSystemLocalTime();
};
} /* namespace qyh */
#endif /* CSYSTEMTIME_H_ */
CSystemTime.cpp
/*
* CSystemTime.cpp
*
* Created on: 2014-3-12
* Author: qinyinghao
*/
#include "CSystemTime.h"
namespace qyh
{
CSystemTime::CSystemTime()
{
}
CSystemTime::~CSystemTime()
{
}
bool CSystemTime::setSystemTime(TIME *_time)
{
struct tm *p = new struct tm();
struct timeval tv;
struct timezone tz;
gettimeofday (&tv , &tz);//获取时区保存tz中
p->tm_year = _time->year - 1900;
p->tm_mon = _time->month - 1;
p->tm_mday = _time->day;
p->tm_hour = _time->hour;
p->tm_min = _time->minute;
p->tm_sec = _time->second;
time_t utc_t = mktime(p);
delete(p);
tv.tv_sec = utc_t;
tv.tv_usec = 0;
if (settimeofday(&tv, &tz) < 0)
{
return false;
}
return true;
}
TIME* CSystemTime::getSystemUTCTime()
{
TIME *t = new TIME();
time_t timep;
struct tm *p;
time(&timep);
p = gmtime(&timep); //获取UTC时间
t->year = 1900 + p->tm_year;
t->month = 1 + p->tm_mon;
t->day = p->tm_mday;
t->hour = p->tm_hour;
t->minute = p->tm_min;
t->second = p->tm_sec;
return t;
}
TIME* CSystemTime::getSystemLocalTime()
{
TIME *t = new TIME();
time_t timep;
struct tm *p;
time(&timep);
p = localtime(&timep); //取得当地时间
t->year = 1900 + p->tm_year;
t->month = 1 + p->tm_mon;
t->day = p->tm_mday;
t->hour = p->tm_hour;
t->minute = p->tm_min;
t->second = p->tm_sec;
return t;
}
} /* namespace qyh */