C++的时间

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

转载于:https://my.oschina.net/chen106106/blog/45570

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值