C 语言中的日期和时间函数218
C 语言提供了广泛的日期和时间函数,允许程序员处理和操作日期和时间值。这些函数定义在 <time.h> 头文件中。
获取当前日期和时间
以下函数可用于获取当前日期和时间:
time():返回当前时间,从 1970 年 1 月 1 日午夜开始的秒数。
ctime():将 time() 返回的秒数转换为人类可读的字符串。
gmtime():将 time() 返回的秒数转换为格林威治标准时间 (GMT) 的 tm 结构。
localtime():将 time() 返回的秒数转换为本地时区的 tm 结构。
格式化日期和时间
以下函数用于格式化日期和时间:
strftime():将 tm 结构中的日期和时间值格式化为字符串。
asctime():将 tm 结构中的日期和时间值格式化为以换行符结尾的字符串。
ctime():将当前时间格式化为以换行符结尾的字符串,类似于 asctime()。
转换日期和时间
以下函数用于转换日期和时间值:
mktime():将 tm 结构中的日期和时间值转换为从 1970 年 1 月 1 日午夜开始的秒数。
strptime():将字符串解析为 tm 结构中的日期和时间值。
gmtime():将从 1970 年 1 月 1 日午夜开始的秒数转换为格林威治标准时间 (GMT) 的 tm 结构。
localtime():将从 1970 年 1 月 1 日午夜开始的秒数转换为本地时区的 tm 结构。
示例
以下代码示例演示了如何使用一些 C 语言日期和时间函数:```c
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm *current_time_info;
// 获取当前时间
current_time = time(NULL);
// 将当前时间转换为本地时区的 tm 结构
current_time_info = localtime(¤t_time);
// 以可读的格式打印日期和时间
printf("当前日期和时间:%s", asctime(current_time_info));
// 获取当前年份
int current_year = current_time_info->tm_year + 1900;
printf("当前年份:%d", current_year);
// 设置tm结构中的日期和时间
current_time_info->tm_year = 2023;
current_time_info->tm_mon = 3; // 0-based,因此 4 表示 5 月
current_time_info->tm_mday = 10;
current_time_info->tm_hour = 14;
current_time_info->tm_min = 30;
current_time_info->tm_sec = 0;
// 将 tm 结构转换为秒数
current_time = mktime(current_time_info);
// 打印已设置日期和时间的秒数
printf("已设置日期和时间的秒数:%ld", current_time);
return 0;
}
```
以上示例输出:```
当前日期和时间:周四 5月 10 14:30:00 2023年
当前年份:2023
已设置日期和时间的秒数:1683844200
```
2024-10-12
上一篇:C 语言绘制三角形的全面指南
下一篇:C 语言之逆序输出数组元素

C语言输出语句地址详解及应用
https://www.shuihudhg.cn/124089.html

高效地将PHP数组写入MySQL数据库
https://www.shuihudhg.cn/124088.html

Python高效读写文件与split函数详解:从基础到进阶
https://www.shuihudhg.cn/124087.html

Java数组冒泡排序详解:算法原理、代码实现及优化策略
https://www.shuihudhg.cn/124086.html

PHP 获取对应 ID 的数据:高效方法与最佳实践
https://www.shuihudhg.cn/124085.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