C++与系统时间相关的函数定义在头文件中

time(time_t*)函数

函数定义如下:

time_t time (time_t* timer);

获取系统当前日历时间 UTC 1970-01-01 00:00:00 开始的 unix 时间戳

参数:timer 存取结果的时间指针变量,类型为 time_t,指针变量可以为 null。如果 timer 指针非 null,则 time()函数返回值变量与 timer 指针一样,都指向同一个内存地址;否则如果 timer 指针为 null,则 time()函数返回一个 time_t 变量时间。
返回值,如果成功,获取当前系统日历时间,否则返回 -1

结构体 struct tm

这里有几个地方要注意:

  1. tm_sec 在 C89 的范围是[0-61],在 C99 更正为[0-60]。通常范围是[0-59],只是某些系统会出现 60 秒的跳跃。
  2. tm_mon 是从零开始的,所以一月份为 0,十二月份为 11。

本地时间转换函数 localtime(time_t*)

函数原型

struct tm * localtime (const time_t * timer);

将日历时间转换为本地时间,从 1970 年起始的时间戳转换为 1900 年起始的时间结构体

源码及编译

current_time.cpp

#include <iostream> 
#include <ctime> 
using namespace std;
int main(int argc, char* argv[]) {
    
time_t rawtime; 
struct tm *pt; 
time(&rawtime); 
pt = localtime(&rawtime); 
cout<<"current: \n"<< pt->tm_year + 1900<<"-"
<<pt->tm_mon + 1<<"-"
<<pt->tm_mday<<" "
<<pt->tm_hour<<":"
<<pt->tm_min<<":"
<<pt->tm_sec<<endl; 
return 0; 
}

编译及运行
current: 2021-06-23 19:32:46

附:参考代码

#include<ctime>
#include<iostream>
using namespace std;
int main()
{
   
time_t rawtime;
struct tm *ptminfo;
time(&rawtime);
ptminfo=localtime(&rawtime);
cout<<ptminfo->tm_year+1900<<'-'
<<ptminfo->tm_mon+1<<'-'
<<ptminfo->tm_mday<<endl;
cout<<ptminfo->tm_hour<<':'
<<ptminfo->tm_min<<':'
<<ptminfo->tm_sec<<endl;
return 0; 
}