Saturday, September 6, 2014

Unix Prog: Time and Date(3)

1. asctime, ctime

Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/time.h  
 ......  
 /* Return a string of the form "Day Mon dd hh:mm:ss yyyy\n"  
   that is the representation of TP in this format. */  
 extern char *asctime (const struct tm *__tp) __THROW;  
   
 /* Equivalent to `asctime (localtime (timer))'. */  
 extern char *ctime (const time_t *__timer) __THROW;  
 ......  

Example, time.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<time.h>  
   
 int main(int argc, char* argv[])  
 {  
  time_t tv;  
  struct tm *tp;  
   
  if((tv = time(NULL)) < 0) {  
   printf("time error!\n");  
   exit(1);  
  }  
   
  if((tp = localtime(&tv)) == NULL) {  
   printf("local time error!\n");  
   exit(2);  
  }  
   
  printf("asctime: %s", asctime(tp));  
  printf("ctime: %s", ctime(&tv));  
   
  exit(0);  
 }  

shell:
1) Run the program without setting the timezone
2) Run the program while setting the timezone

This indicates that asctime, ctime are affected by time zone information.
 ubuntu@ip-172-31-23-227:~$ ./time.out  
 asctime: Sat Sep 6 20:20:44 2014  
 ctime: Sat Sep 6 20:20:44 2014  
 ubuntu@ip-172-31-23-227:~$ TZ=EST5EDT ./time.out  
 asctime: Sat Sep 6 16:20:51 2014  
 ctime: Sat Sep 6 16:20:51 2014  

2. strftime

definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/time.h  
 ......  
 /* Format TP into S according to FORMAT.  
   Write no more than MAXSIZE characters and return the number  
   of characters written, or 0 if it would exceed MAXSIZE. */  
 extern size_t strftime (char *__restrict __s, size_t __maxsize,  
             const char *__restrict __format,  
             const struct tm *__restrict __tp) __THROW;  
 ......  

example:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<time.h>  
   
 int main(int argc, char* argv[])  
 {  
  time_t tv;  
  struct tm *tp;  
   
  if((tv = time(NULL)) < 0) {  
   printf("time error!\n");  
   exit(1);  
  }  
   
  if((tp = localtime(&tv)) == NULL) {  
   printf("local time error!\n");  
   exit(2);  
  }  
   
  int no;  
  char buf[200];  
  if((no = strftime(buf, 200, "%F %r", tp)) == 0) {  
   printf("strftime error!\n");  
   exit(3);  
  }  
  printf("formated time: %s\n", buf);  
   
  exit(0);  
 }  

shell:
1) Run the program without setting timezone, localtime by default will return the UTC time
2) Run the program with setting timezone.
 ubuntu@ip-172-31-23-227:~$ ./time.out  
 formated time: 2014-09-06 08:34:00 PM  
 ubuntu@ip-172-31-23-227:~$ TZ=EST5EDT ./time.out  
 formated time: 2014-09-06 04:34:04 PM  

No comments:

Post a Comment