C and C++ how do I get an example of the current system time

  • 2020-05-27 06:40:39
  • OfStack

C/C++ how do I get an example of the current system time

The system time dependent functions in the C library are defined in < time.h > In the header file, C++ is defined in < ctime > In the header file.

1. time time_t * () function

The function definition is as follows:


time_t time (time_t* timer);

Gets the unix timestamp starting at the current system calendar time UTC 1970-01-01 00:00:00

Parameter: timer access result time pointer variable of type time_t, pointer variable can be null. If the timer pointer is not null, the time() function returns a value variable that points to the same memory address as the timer pointer 1. Otherwise, if the timer pointer is null, the time() function returns an time_t variable time.

Returns value, if successful, gets the current system calendar time, otherwise returns -1.

2. Structure struct tm

变量 类型 说明 范围
tm_sec int 每分钟的秒数 [0 - 61]
tm_min int 每小时后面的分钟数 [0 - 59]
tm_hour int 凌晨开始的小时数 [0 - 23]
tm_mday int 从每月份开始算的天数 [1 - 31]
tm_mon int 从1月份开始的月份数 [0 - 11]
tm_year int 从1900年开始的年数  
tm_wday int 从每周天开始算的天数 [0 - 6]
tm_yday int 1年的第几天,从零开始 [0 - 365]
tm_isdst int 夏令时  
       

Here are a few things to note:

1. The range of tm_sec in C89 is [0-61], which is corrected to [0-60] in C99. The usual range is [0-59], with some systems having 60-second jumps.

2. tm_mon starts from zero, so January is 0 and November 102 is 11.

3. Local time conversion function localtime(time_t*)

The function prototype


struct tm * localtime (const time_t * timer);

Convert calendar time to local time, from a timestamp starting in 1970 to a time data structure starting in 1900

4. Source code and compilation

current_time.cpp


#include <cstdio> 
#include <ctime> 
 
int main(int argc, char* argv[]) { 
  time_t rawtime; 
  struct tm *ptminfo; 
 
  time(&rawtime); 
  ptminfo = localtime(&rawtime); 
  printf("current: %02d-%02d-%02d %02d:%02d:%02d\n", 
      ptminfo->tm_year + 1900, ptminfo->tm_mon + 1, ptminfo->tm_mday, 
      ptminfo->tm_hour, ptminfo->tm_min, ptminfo->tm_sec); 
  return 0; 
} 

Compile and run


$ g++ current_time.cpp

$ ./a.out

current: 2017-07-26 23:32:46

The above is C/C++ how to get the current system time example details, if you have any questions please leave a message or to the site community exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: