c++关于ctime那些事儿

库函数

C++的标准库没用给具体时间日期的函数,而是用了c中的时间日期的函数,比如说之前提到的那个C++随机点名软件,就用到了ctime中的随机数种子。


#include <iostream>
#include <ctime>
 
using namespace std;
 
int main( )
{
   // 这个是随电脑的时间
   time_t now = time(0);
   
   // 把 now 转换为字符串形式
   char* dt = ctime(&now);
 
   cout << "本地日期和时间:" << dt << endl;
 
   // 把 now 转换为 time 结构
   tm *gmtm = gmtime(&now);
   dt = asctime(gmtm);
   cout << " 日期和时间:"<< dt << endl;
}

tm是格式化时间的操作,我们看到的大多数时间函数,都会用到tm结构,下面的实例使用了 tm 结构和各种与日期和时间相关的函数。只需要了解C/C++的基本语法,相信不难看懂。


#include <iostream>
#include <ctime>
 
using namespace std;
 
int main( )
{
   time_t now = time(0);
   cout << "1970 到目前经过秒数:" << now << endl;
   tm *ltm = localtime(&now);
   // 挨个输出 tm 结构的各个组成部分
   cout << "年: "<< 1900 + ltm->tm_year << endl;
   cout << "月: "<< 1 + ltm->tm_mon<< endl;
   cout << "日: "<<  ltm->tm_mday << endl;
   cout << "时间: "<< ltm->tm_hour << ":";
   cout << ltm->tm_min << ":";
   cout << ltm->tm_sec << endl;
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值