用c语言实现一个函数参数为秒数值根据自2000年1月1日 00:00:00以来的秒数值计算当前的日期和时间
由于题目中没有明确要求输出的格式,以下代码输出的日期格式为年-月-日 时:分:秒。
#include <stdio.h>
#include <time.h>
void calculateDateTime(long int seconds) {
struct tm timeinfo;
timeinfo.tm_year = 100; // 2000年对应的年份为100
timeinfo.tm_mday = 1;
time_t rawtime = mktime(&timeinfo) + seconds; // 计算当前的时间戳
struct tm *ptm = localtime(&rawtime);
char datetime[20];
strftime(datetime, 20, "%Y-%m-%d %H:%M:%S", ptm);
printf("当前的日期和时间:%s\n", datetime);
}
int main() {
long int seconds = 1830177600L; // 2028年9月1日 @ 00:00:00 对应的秒数
calculateDateTime(seconds);
return 0;
}
上述代码中,我们使用了 struct tm 类型的结构体变量 timeinfo,并将其初始化为 2000 年 1 月 1 日的日期信息。接着,我们使用 mktime 函数将 timeinfo 转换成时间戳,并加上题目中给定的秒数值,得到当前的时间戳。最后,我们使用 localtime 函数将时间戳转换成本地时间,然后使用 strftime 函数将日期时间格式化成字符串,并输出到控制台
原文地址: https://www.cveoy.top/t/topic/cowY 著作权归作者所有。请勿转载和采集!