菜鸟自学ARM:linux下编程获取系统时间和设置时间

转:http://hi.baidu.com/guan9527/blog/item/2831c5ec1632eadcb31cb1b5.html

菜鸟自学ARM:linux下编程获取系统时间和设置时间
2009-04-09 21:51

获取时间有几种编程方法:

1

#include <stdio.h>
#include <time.h>
main(){
   time_t t;
   struct tm *p;
   time(&t);
   p=gmtime(&t);
   printf("Year :%d\n",1900+p->tm_year);
   printf("Month :%d\n",1+p->tm_mon);
   printf("Day   :%d\n",p->tm_mday);
   printf("Hour :%d\n",p->tm_hour);
   printf("Minute:%d\n",p->tm_min);
   printf("Second:%d\n",p->tm_sec);
   printf("Weekday:%d\n",p->tm_wday);
   printf("Days :%d\n",p->tm_yday);
   printf("Isdst :%d\n",p->tm_isdst);

}

 

2

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
time_t p;
char s[30];
time(&p);
strcpy(s,ctime(&p)) ;
printf("%s\n",s);

}

 

3

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
time_t p;
char s[30];
struct gm *q;
time(&p);
q=gmtime(&p);
strcpy(s,asctime(q)) ;
printf("%s\n",s);

}

 

设置时间:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>
main()
{
     time_t t;
     struct tm *p;
     int i;
     struct timeval tv;
     struct timezone tz;
     tz.tz_minuteswest=0;
     tz.tz_dsttime=0;
     time(&p);
     p=gmtime(&t);
     printf("Change your time:\n");
     printf("Year:\n");
     scanf("%d",&i);
     (*p).tm_year=i-1900;
     printf("Month:\n");
     scanf("%d",&i);
     (*p).tm_mon=i-1;  
     printf("Date:\n");
     scanf("%d",&i);
     (*p).tm_mday=i;     
     printf("Hour:\n");
     scanf("%d",&i);
     (*p).tm_hour=i;
     printf("Minute:\n");
     scanf("%d",&i);
     (*p).tm_min=i;
     printf("Second:\n");
     scanf("%d",&i);
     (*p).tm_sec=i;
     t=mktime(p);
     tv.tv_sec=t;
     tv.tv_usec=0;
     settimeofday (&tv , &tz);
     printf("Done!\n");
}

 

你可能感兴趣的:(编程,linux,include,自学,休闲)