帮我用c 写一个日期类包年月日时分秒可以事实变化打印在终端
以下是一个简单的日期类的示例代码,包含年月日时分秒,并且可以实时更新并打印在终端上:
#include <stdio.h>
#include <time.h>
typedef struct {
int year;
int month;
int day;
int hour;
int minute;
int second;
} Date;
void print_date(Date d);
int main() {
Date current_date;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
current_date.year = tm.tm_year + 1900;
current_date.month = tm.tm_mon + 1;
current_date.day = tm.tm_mday;
current_date.hour = tm.tm_hour;
current_date.minute = tm.tm_min;
current_date.second = tm.tm_sec;
while (1) {
t = time(NULL);
tm = *localtime(&t);
current_date.year = tm.tm_year + 1900;
current_date.month = tm.tm_mon + 1;
current_date.day = tm.tm_mday;
current_date.hour = tm.tm_hour;
current_date.minute = tm.tm_min;
current_date.second = tm.tm_sec;
print_date(current_date);
printf("\n");
sleep(1); // 暂停 1 秒钟
}
return 0;
}
void print_date(Date d) {
printf("%04d-%02d-%02d %02d:%02d:%02d", d.year, d.month, d.day, d.hour, d.minute, d.second);
}
代码中使用了 time.h 库中的 time() 和 localtime() 函数来获取当前时间,并将其转换为年月日时分秒的形式。然后使用一个无限循环来实时更新日期,并使用 print_date() 函数将日期打印在终端上。在每次循环结束时,使用 sleep() 函数暂停一秒钟,以便观察到日期的变化。
原文地址: https://www.cveoy.top/t/topic/bOHi 著作权归作者所有。请勿转载和采集!