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;
}

发布了25 篇原创文章 · 获赞 60 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/EIDoradol/article/details/105385014
今日推荐