您的位置:首页 > 其它

BOOST:使用local_date_time 计算当前时间戳

2010-07-08 10:31 597 查看
在工作中,我们经常使用时间戳,来标示些特性,昨天也正好有个同事问我,所以想起用这个办法。

原理:取得现在时间的utc - 纪元时间。

#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
using namespace std;
using namespace boost::gregorian;
using namespace boost::local_time;
using namespace boost::posix_time;
int main()
{
tz_database tz_db;
try
{
/*
*加载时区数据库
*/
tz_db.load_from_file("/usr/local/boost_1_42_0/libs/date_time/data/date_time_zonespec.csv");
}
catch(data_not_accessible dna)
{
std::cerr << "Error with time zone data file: " << dna.what() << std::endl;
exit(EXIT_FAILURE);
}
catch(bad_field_count bfc)
{
std::cerr << "Error with time zone data file: " << bfc.what() << std::endl;
exit(EXIT_FAILURE);
}
/*
*由于没有找到北京,我们暂时指向重庆
*/
time_zone_ptr time_zone = tz_db.time_zone_from_region("Asia/Chongqing");
const time_t tt = time(NULL);
tm* pLocalTime = localtime(&tt);
date record_date(pLocalTime->tm_year+1900,pLocalTime->tm_mon+1,pLocalTime->tm_mday);
time_duration record_time(pLocalTime->tm_hour,pLocalTime->tm_min,pLocalTime->tm_sec);
/*
*本地当前时间
*/
local_date_time time_t_now(record_date,
record_time,
time_zone,
local_date_time::NOT_DATE_TIME_ON_ERROR);
std::cout << "localtime:[" << time_t_now << "]" << std::endl;
/*
*纪元时间
*/
ptime time_t_begin(date(1970,1,1));
time_duration timestamp = time_t_now.utc_time() - time_t_begin;
cout << "timestamp:[" << timestamp.total_seconds() << "]" << endl ;


这是构造函数的声明,所在<boost/date_time/local_time/local_date_time.hpp>中

/*! This constructs a local time -- the passed time information
* understood to be in the passed tz.  The DST flag is calculated
* according to the specified rule.
*/
local_date_time_base(date_type d,
time_duration_type td,
boost::shared_ptr<tz_type> tz,
DST_CALC_OPTIONS calc_option) :
// dummy value - time_ is set in constructor code
date_time::base_time<utc_time_type,time_system_type>(utc_time_type(d,td)),
zone_(tz)


运行结果:

[root@localhost bin]# ./date
localtime:[2010-Jul-08 09:32:18 CST]
timestamp:[1278552738]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐