实现了localtime 和 UTCtime的转换:
Linux多线程编程工具库liblmp_tool github: https://github.com/Dwyane05/liblmp_tool
Timezone类分析:
头文件;定义了localtime和utctime 的转换;使用了shard_ptr 智能指针处理date
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* TimeZone.h
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#ifndef LMP_TOOL_TIMEZONE_H
#define LMP_TOOL_TIMEZONE_H
#include "copyable.h"
#include <memory>
#include <time.h>
namespace lmp_tool
{
// TimeZone for 1970~2030
class TimeZone : public lmp_tool::copyable
{
public:
explicit TimeZone(const char* zonefile);
TimeZone(int eastOfUtc, const char* tzname); // a fixed timezone
TimeZone() = default; // an invalid timezone
// default copy ctor/assignment/dtor are Okay.
bool valid() const
{
// 'explicit operator bool() const' in C++11
return static_cast<bool>(data_);
}
struct tm toLocalTime(time_t secondsSinceEpoch) const;
time_t fromLocalTime(const struct tm&) const;
// gmtime(3)
static struct tm toUtcTime(time_t secondsSinceEpoch, bool yday = false);
// timegm(3)
static time_t fromUtcTime(const struct tm&);
// year in [1900..2500], month in [1..12], day in [1..31]
static time_t fromUtcTime(int year, int month, int day,
int hour, int minute, int seconds);
struct Data;
private:
std::shared_ptr<Data> data_;
};
} // namespace lmp_tool
#endif // LMP_TOOL_TIMEZONE_H
具体代码实现太多就不粘贴了,见GitHub:lmp_src目录下
测试代码:
测试几个主要城市 的时间
#include "TimeZone.h"
#include "Common.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
using lmp_tool::TimeZone;
struct tm getTm(int year, int month, int day,
int hour, int minute, int seconds)
{
struct tm gmt;
lmp_tool::memZero(&gmt, sizeof gmt);
gmt.tm_year = year - 1900;
gmt.tm_mon = month - 1;
gmt.tm_mday = day;
gmt.tm_hour = hour;
gmt.tm_min = minute;
gmt.tm_sec = seconds;
return gmt;
}
struct tm getTm(const char* str)
{
struct tm gmt;
lmp_tool::memZero(&gmt, sizeof gmt);
strptime(str, "