[英]How to get current time in C using gettime()?
我们需要使用gettime()
来获取 C 中的当前时间。我试图打印当前时间但错误:
错误:“t”的存储大小未知
发生。 我不知道如何解决这个问题。 这是代码:
#include<stdio.h>
#include<dos.h>
int main(){
struct time t;
gettime(&t);
printf("%d:%d:%d", t.ti_hour,t.ti_min,t.ti_sec);
getch();
return 0;
}
目前尚不清楚您是要获取时间,还是只是打印出来。
对于第二种情况,很少有遗留方法可以提供格式化时间( asctime
、 ctime
)。 但这些可能不符合您的需求。
更灵活的选择是使用基于来自 time/localtime_r 的数据的strftime
。 strftime 支持许多可用于 GNU 日期的转义 (%Y, ...)。
#include <stdio.h>
#include <time.h>
void main(void)
{
time_t now = time(NULL) ;
struct tm tm_now ;
localtime_r(&now, &tm_now) ;
char buff[100] ;
strftime(buff, sizeof(buff), "%Y-%m-%d, time is %H:%M", &tm_now) ;
printf("Time is '%s'\n", buff) ;
}
获取本地时间的标准 C 函数只是time
,包含在头文件 time.h 中
示例取自此处。
/* time example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t timer;
struct tm y2k = {0};
double seconds;
y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_sec = 0;
y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;
time(&timer); /* get current time; same as: timer = time(NULL) */
seconds = difftime(timer,mktime(&y2k));
printf ("%.f seconds since January 1, 2000 in the current timezone", seconds);
return 0;
}
有关不同时间格式的更多信息:
好的,您正在尝试使用 DOS.H 库,因此 time.h 和 ctime 库不适用于此特定问题,因为 DOS.H 是一个专有的 C 库,您不能在任何其他 C(C++ 或C#),请在阅读这篇文章后阅读库,以便您清楚地看到我在说什么,所以在 DOS.H 库中是一个用于保存所有时间变量的 STRUCT,这是小时,分钟,秒,所以我们要做的第一件事是声明一个允许我们保存此类数据的变量:
结构时间 tm;
完成此操作后,您可以使用库中的 gettime() 函数来将 que 值保存在我们可以访问的位置:
获取时间(&tm);
最后要打印 o 随心所欲地使用这些数据,您需要获取结构的每个寄存器:
printf("系统时间为:%d : %d : %d\\n",tm.ti_hour, tm.ti_min, tm.ti_sec);
检查此代码:
#include<stdio.h>
#include<dos.h>
#include<conio.h>
int main()
{
struct date fecha;
struct time hora;
union REGS regs;
getdate(&fecha);
printf("La fecha del sistema es: %d / %d / %d\n",fecha.da_day,fecha.da_mon,fecha.da_year);
regs.x.cx = 0x004c;
regs.x.dx = 0x4b40;
regs.h.ah = 0x86; /* 004c4b40h = 5000000 microsegundos */
int86(0x15,®s,®s); /* Interrupcion 15h suspension de sistema */
gettime(&hora);
printf("la hora del sistema es: %d : %d : %d\n",hora.ti_hour,hora.ti_min,hora.ti_sec);
getche();
clrscr();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.