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)
原文链接: http://blog.csdn.net/sheismylife/article/details/6772477