std命名空间
绝大多数C++中的时间类型以及函数都只是重用了C的,仅仅是位于std命名空间中。要使用C++时间,首先要include <ctime>文件。看一下ctime文件内容,会发现包含了time.h文件。
#pragma GCC system_header
#include <bits/c++config.h>
#include <time.h>
#ifndef _GLIBCXX_CTIME
#define _GLIBCXX_CTIME 1
// Get rid of those macros defined in <time.h> in lieu of real functions.
#undef clock
#undef difftime
#undef mktime
#undef time
#undef asctime
#undef ctime
#undef gmtime
#undef localtime
#undef strftime
namespace std
{
using ::clock_t;
using ::time_t;
using ::tm;
using ::clock;
using ::difftime;
using ::mktime;
using ::time;
using ::asctime;
using ::ctime;
using ::gmtime;
using ::localtime;
using ::strftime;
} // namespace
#endif
没有timeval结构,保留了time_t类型和tm结构。还有一些函数。有了前面一篇<<C的时间>>的基础。运用这些是非常容易的。C++程序员为了保持风格的一致性,应该尽可能的使用ctime文件,只是需要知道这些类型和函数其实来自于C的就行了。
asctime可以将tm转成字符串,参考:http://www.cplusplus.com/reference/clibrary/ctime/asctime/
/* asctime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "The current date/time is: %s", asctime (timeinfo) );
return 0;
}
MySQL++
MySQL++提供了DateTime和Date类型,也提供了比较函数。参考文档即可:
http://tangentsoft.net/mysql++/doc/html/refman/classmysqlpp_1_1DateTime.html
http://tangentsoft.net/mysql++/doc/html/refman/datetime_8h-source.html
值得注意的是这两个类都提供了类型转换操作符
operator time_t() const;
因此可以通过强制转换将它们转换成秒数。
它们的构造函数也都能够接受time_t参数,可以将秒数转换成对象。
CppDB
CppDB没有定义自己的时间类型,直接使用了std::tm,比如下面的代码:
bool cppdb::result::fetch(int col,std::tm & v)
MongoDB
MongoDB采用了C风格的time_t,如下:
BSONObjBuilder & appendTimeT (const StringData &fieldName, time_t dt)
但是注意API Reference提到time_t是C风格的32bit整数。实际上我们在64bit系统上开发的时候epoch都是long int,是64bit的。为了一直起来,保存到MongoDB中可以直接当保存为Timestamp, 因为它是unsigned long long(uint64_t),而不是用time_t,比如下面的方法:
mongo::BSONObjBuilder builder;
builder.appendTimestamp("epoch", cpu.epoch);
builder.appendTimestamp("total_jiffies", cpu.total_jiffies);
builder.appendTimestamp("work_jiffies", cpu.work_jiffies);
MongoDB还有一种特殊的时间用法。_id实际上是ObjectId,是一个24个字符组成的字符串。前面8个16进制字符表示时间,1970年到创建本行记录的秒数。有了这个特点后,有些情况下记录不一定要添加时间字段,用_id就可以了。
查询时间范围的时候,按照下面的方法:
1. 生成表示开始时间的秒数
2.转成16进制的8个字符的字符串
3.字符串后面拼接“0000000000000000”, 16个0组成。
4.用拼接后的字符串创建ObjectId:
mongo::OID(t1)
5.然后用$gte运算符
同样的方法用于结束时间的查询,最后代码参考如下:
BSONObjBuilder condition;
condition.append("user_id",mongo::OID(user_id));
condition.append("display_id",mongo::OID(display_id));
if ( t1 == "-1" && t2 == "-1") {
//do nothing
} else {
BSONObjBuilder c1;
c1.append("$gte", mongo::OID(t1));
condition.append("_id", c1.obj());
BSONObjBuilder c2;
c2.append("$lte", mongo::OID(t2));
condition.append("_id", c2.obj());
}