time.h是C/C++中用于操纵日期和时间的头文件,提供了相关函数以供使用。本篇文章将重点介绍time.h头文件中的几个常见函数。

1. time()函数

函数原型:

time_t time(time_t t);

函数说明:

  • time_t是一个long int类型的变量,用于存储时间。
  • 此函数返回距1970年1月1日00:00:00 UTC时间以来经过的秒数。
  • 如果t不为null,则不仅返回当前时间,还将结果存储在t指向的内存中。

函数返回值:如果成功,则返回秒数;如果失败,则返回-1,并将错误信息保存在errno中。

示例程序:

include <stdio.h>
include <time.h>
int main() {
  time_t current_time;
  time(&current_time);
  printf("当前时间:%ld\n", current_time);
  return 0;
}

输出结果:1669765623

2. gmtime()函数

函数原型:

struct tm gmtime(const time_t timep);

函数说明:

  • 此函数将timep指向的time_t时间转换为格林尼治标准时间(UTC)下的年月日时间。
  • 转换后的时间结构存储在tm结构中。

结构定义:

typedef struct tm {
  int tm_sec;      // 秒数 [0,59]
  int tm_min;      // 分数 [0,59]
  int tm_hour;     // 小时数 [0,23]
  int tm_mday;     // 月中的天数 [1,31]
  int tm_mon;      // 月份 [0,11]
  int tm_year;     // 年份 [1900开始]
  int tm_wday;     // 星期几 [0(星期日),6]
  int tm_yday;     // 年中的天数 [0,365]
  int tm_isdst;    // 夏令时标志 [0,1]
} tm;

函数返回值:返回指向填充了UTC时间的tm结构的指针。

示例程序:

include <stdio.h>
include <time.h>
int main() {
  time_t current_time;
  time(&current_time);
  struct tm utc_time = gmtime(&current_time);
  printf("UTC时间:%s\n", asctime(utc_time));
  return 0;
}

输出结果:Sat May 27 11:43:45 2023

3. localtime()函数

函数原型:

struct tm localtime(const time_t timep);

函数说明:

  • 此函数将timep指向的time_t时间转换为本地时间。
  • 转换后的时间结构存储在tm结构中。

函数返回值:返回指向填充了本地域时间的tm结构的指针。

示例程序:

include <stdio.h>
include <time.h>
int main() {
  time_t current_time;
  time(&current_time);
  struct tm local_time = localtime(&current_time);
  printf("本地时间:%s\n", asctime(local_time));
  return 0;
}

输出结果:Sat May 27 19:13:45 2023

4. ctime()函数

函数原型:

char ctime(const time_t timep);

函数说明:

  • 此函数将timep指向的time_t时间转换为以字符串形式表示的本地时间。
  • 转换后的时间字符串格式为:星期 月 日 小时:分钟:秒 年

函数返回值:返回指向时间字符串的指针。

示例程序:

include <stdio.h>
include <time.h>
int main() {
  time_t current_time;
  time(&current_time);
  char time_str = ctime(&current_time);
  printf("本地时间字符串:%s\n", time_str);
  return 0;
}

输出结果:Sat May 27 19:17:45 2023

5. asctime()函数

函数原型:

char asctime(const struct tm timeptr);

函数说明:

  • 此函数将timeptr指向的tm时间结构转换为以字符串形式表示的本地时间。
  • 转换后的时间字符串格式为:星期 月 日 小时:分钟:秒 年

函数返回值:返回指向时间字符串的指针。

示例程序:

include <stdio.h>
include <time.h>
int main() {
  time_t current_time;
  time(&current_time);
  struct tm local_time = localtime(&current_time);
  char time_str = asctime(local_time);
  printf("本地时间字符串:%s\n", time_str);
  return 0;
}

输出结果:Sat May 27 19:22:32 2023

需要注意的是,time.h头文件中的