2017-02-21 58 views
0

我的程序找到当前系统日期和时间是如何在结构中存储当前系统日期?

#include<stdio.h> 
#include<time.h> 
struct date{ 
int day,month,year; 
}; 
main() 
{ 
    time_t t; 
    time(&t); 
    printf("Today's date and time is %s",ctime(&t)); 


} 

,我想这个存储当前的日期构建请给我一个建议。

+4

首先写入有效的C.'int main(void)'而不是'main()' – StoryTeller

+0

我建议你看看例如。 [这次函数和结构参考](http://en.cppreference.com/w/c/chrono)。 –

+1

您应该计划使用['localtime()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/localtime.html)或 [''gmtime()'](http:// pubs.opengroup.org/onlinepubs/9699919799/functions/gmtime.html),取决于你想要本地时间还是UTC。请注意,您必须映射值 - 年和月可能不是您期望的数字,直到您仔细阅读手册。 –

回答

3

标准库已经具有像您的结构:struct tm<time.h>

 int tm_sec;  /* seconds (0 - 60) */ 
     int tm_min;  /* minutes (0 - 59) */ 
     int tm_hour; /* hours (0 - 23) */ 
     int tm_mday; /* day of month (1 - 31) */ 
     int tm_mon;  /* month of year (0 - 11) */ 
     int tm_year; /* year - 1900 */ 
     int tm_wday; /* day of week (Sunday = 0) */ 
     int tm_yday; /* day of year (0 - 365) */ 
     int tm_isdst; /* is summer time in effect? */ 
     char *tm_zone; /* abbreviation of timezone name */ 
     long tm_gmtoff; /* offset from UTC in seconds */ 

该库提供了由功能localtime填(你的时间区)和gmtime(为GMT时间)struct tm类型的全局变量。

C11还指定了localtime_sgmtime_s,它们避免了与全局变量相关的问题,但我不知道它们得到了多大的支持。 POSIX也指定类似的gmtime_rlocaltime_r

相关问题