欢迎来到我的博客https://www.cnblogs.com/veis/

https://www.cnblogs.com/veis/p/14182037.html

linux获取系统时间

linux获取系统时间

0.相关结构体介绍

// Broken-down time is stored in the structure tm, which is defined in <time.h> as follows:
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
/*
tm_sec The number of seconds after the minute, normally in the range 0 to 59, but can be
up to 60 to allow for leap seconds.

tm_min The number of minutes after the hour, in the range 0 to 59.

tm_hour The number of hours past midnight, in the range 0 to 23.

tm_mday The day of the month, in the range 1 to 31.

tm_mon The number of months since January, in the range 0 to 11.

tm_year The number of years since 1900.

tm_wday The number of days since Sunday, in the range 0 to 6.

tm_yday The number of days since January 1, in the range 0 to 365.

tm_isdst A flag that indicates whether daylight saving time is in effect at the time
described. The value is positive if daylight saving time is in effect, zero if it
is not, and negative if the information is not available.
*/

1.使用步骤

(1)包含time.h头文件

(2)通过time函数获取时间到time_t对象中

(3)通过gmtime函数吧time_t中的内容格式化到struct tm结构体对象中

2.示例代码

#include <stdio.h>
#include <time.h>

int main(int argc, char const *argv[])
{
  time_t t;
  struct tm *p_time = NULL;

  time(&t);
  p_time = gmtime(&t);
  if(NULL != p_time)
    printf("%04d年%02d月%02d日:%02d时%02d分%02d秒\n",
      (1900+p_time->tm_year), p_time->tm_mon, p_time->tm_mday,
      (8+p_time->tm_hour), p_time->tm_min, p_time->tm_sec);
  else
    printf("获取时间失败!\n");

  return 0;
}

 注:年需要加上偏移量1900,小时需要加上偏移量8

posted @ 2022-02-04 22:35  veis  阅读(576)  评论(0编辑  收藏  举报