这是对我创建的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);
}
Run Code Online (Sandbox Code Playgroud)
我第一次运行该程序的时间是10:56.42,但print_time函数显示为2:56.42。我该如何解决?
我尝试(t % (60*60*60))/(60*60)从中减去12并打印出来,然后打印出正确的时间,但是当时间更改11为时,时间显示为9。
60*60*60表示60个小时,而不是一天。您想要类似的东西:
printf("%d:%.2d.%.2d\n", (t % (24*60*60))/(60*60), (t % (60*60))/60, t % 60);
Run Code Online (Sandbox Code Playgroud)
在法国,此程序会打印正确的时间减去2小时(不考虑将夏时制(+1)添加到UTC(+1))。
我建议您改用标准库函数,例如localtime或gmtime。
time_t t = time(NULL);
struct tm *tstruct = gmtime(&t);
Run Code Online (Sandbox Code Playgroud)
现在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 */
};
Run Code Online (Sandbox Code Playgroud)
您的方法,本地方法和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);
}
Run Code Online (Sandbox Code Playgroud)
印刷品:
15:22.26
15:22.26
17:22.26
Run Code Online (Sandbox Code Playgroud)
看来您的代码现在可以正确模拟UTC时间了。现在,leap年和其他一切都给您带来更多挑战...
如果您不能使用标准库(除外time()),并且想要本地时间,则还必须处理时区。您必须在某些自定义设置中对它进行硬编码(例如操作系统)。