这是对我创建的打印一天中的小时、分钟和秒的 C 库的测试:
#include <time.h>
#include <stdio.h>
time_t print_time(time_t t)
{
if(!t) t = time(NULL);
printf("%d:%.2d.%.2d\n", (t % (60*60*60))/(60*60), (t % (60*60))/60, t % 60);
fflush(stdout);
return t;
}
int main(void)
{
print_time(0);
}
我第一次运行这个程序时是 10:56.42,但是 print_time
函数打印了 2:56.42。我该如何解决这个问题?
我尝试从 12
中减去 (t % (60*60*60))/(60*60)
并打印它,它打印出正确的时间,但是当时间变为11
时,时间打印为9
。
最佳答案
60*60*60
表示 60 小时,而不是一天。你想要这样的东西:
printf("%d:%.2d.%.2d\n", (t % (24*60*60))/(60*60), (t % (60*60))/60, t % 60);
在法国,此程序打印出正确的时间减去 2 小时(不考虑添加到 UTC 的夏令时 (+1)(也是 +1))。
我建议您改用标准库函数,例如 localtime
或 gmtime
。
time_t t = time(NULL);
struct tm *tstruct = gmtime(&t);
现在 tstruct
点在信息上,天,小时,你命名......
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
您的方法、本地和 gm 方法的完整示例:
#include <time.h>
#include <stdio.h>
int main()
{
time_t t = time(NULL);
printf("%d:%.2d.%.2d\n", (t % (24*60*60))/(60*60), (t % (60*60))/60, t % 60);
struct tm *tstruct = gmtime(&t);
printf("%d:%.2d.%.2d\n",tstruct->tm_hour,tstruct->tm_min,tstruct->tm_sec);
tstruct = localtime(&t);
printf("%d:%.2d.%.2d\n",tstruct->tm_hour,tstruct->tm_min,tstruct->tm_sec);
}
打印:
15:22.26
15:22.26
17:22.26
看来您的代码现在可以正确模拟 UTC 时间的小时数。现在更多的挑战是闰年和所有...
如果您不能使用标准库(time()
除外)并且您想要本地时间,您还必须处理时区。您必须在某些自定义设置中对其进行硬编码(就像操作系统那样)。
关于c - 如何修复我的打印时间功能,使其不会慢 8 小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825863/