C 语言时间函数:操作日期和时间381
在 C 语言中,time.h 头文件提供了操作日期和时间的函数。这些函数让你可以获取当前时间、操纵日期和时间结构,以及将日期和时间转换为字符串格式。
获取当前时间
获取当前时间的函数包括:* time():返回自 1970 年 1 月 1 日以来的秒数(Unix 时间戳)。
* localtime():将 Unix 时间戳转换为本地时间结构 tm。
* gmtime():将 Unix 时间戳转换为格林尼治标准时间结构 tm。
tm 结构包含以下成员:
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,星期日为 0)
int tm_yday; // 年中天 (0-365)
int tm_isdst; // 是否为夏令时
};
操纵日期和时间
要操纵日期和时间,可以使用以下函数:* mktime():将 tm 结构转换为 Unix 时间戳。
* strftime():将 tm 结构转换为格式化的字符串。
* strptime():将格式化的字符串解析为 tm 结构。
其他函数
time.h 头文件还提供了其他有用的函数,例如:* difftime():计算两个 Unix 时间戳之间的差值,以秒为单位。
* asctime():将 tm 结构格式化为 ASCII 字符串。
* ctime():将 Unix 时间戳格式化为 ASCII 字符串。
示例
以下示例展示了如何使用 time.h 函数:```c
#include
#include
int main() {
// 获取当前时间
time_t current_time = time(NULL);
// 将当前时间转换为本地时间结构
struct tm *local_time = localtime(¤t_time);
// 打印格式化的日期和时间
printf("当前日期和时间:%s", asctime(local_time));
// 计算从 1970 年 1 月 1 日到当前时间的秒数
long seconds_since_epoch = difftime(current_time, 0);
// 打印秒数
printf("自 1970 年 1 月 1 日以来的秒数:%ld", seconds_since_epoch);
return 0;
}
```
输出:
```
当前日期和时间:日 Apr 5 12:06:32 2023
自 1970 年 1 月 1 日以来的秒数:1649055992
```
2024-10-24
上一篇:C 语言中 if 函数:全面指南
下一篇:C 语言的十进制输出
Python字符串查找与判断:从基础到高级的全方位指南
https://www.shuihudhg.cn/134118.html
C语言如何高效输出字符串“inc“?深度解析printf、puts及格式化输出
https://www.shuihudhg.cn/134117.html
PHP高效获取CSV文件行数:从小型文件到海量数据的最佳实践与性能优化
https://www.shuihudhg.cn/134116.html
C语言控制台图形输出:从入门到精通的ASCII艺术实践
https://www.shuihudhg.cn/134115.html
Python在Linux环境下的执行与自动化:从基础到高级实践
https://www.shuihudhg.cn/134114.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html