struct tm *gmtime_r(time_t *timep, struct tm *result)

时间:2021-09-01 20:39:34

struct tm *gmtime_r(time_t *timep, struct tm *result)

The gmtime_r() is similar to gmtime(), but stores data in user supplied struct.

Examples

  1. current time around the world
  2. use gmtime_r() in a multithreading enviroment

current time around the world   return

program.c   copy

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <time.h>
 
void print_time( struct tm * tm , const char *location, int zone)
{
     int hour;
 
     hour = (24 + tm ->tm_hour + zone) % 24;
     printf ( "%20s: %02d:%02d\n" , location, hour, tm ->tm_min);
}
 
// Mountain Standard Time (MST) is 7 hours behind Coordinated Universal Time.
#define MST -7
 
// Greenwich Mean Time (GMT) has no offset from Coordinated Universal Time.
#define GMT 0
 
// China Standard Time (CST) is 8 hours ahead of Coordinated Universal Time.
#define CST 8
 
int main()
{
     time_t now;
     struct tm tm ;
 
     now = time (NULL);
     // convert 'struct tm' to 'time_t'
     gmtime_r(&now, & tm );
 
     print_time(& tm , "Phoenix, USA" , MST);
     print_time(& tm , "London, England" , GMT);
     print_time(& tm , "Beijing, China" , CST);
     return 0;
}

Output

?
1
2
3
    Phoenix, USA: 05:38
London, England: 12:38
  Beijing, China: 20:38

use gmtime_r() in a multithreading enviroment   return

program.c   copy

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
 
void print_time()
{
     time_t now;
     struct tm tm ;
     char buffer[64];
 
     now = time (NULL);
     gmtime_r(&now, & tm );
     asctime_r(& tm , buffer);
     printf ( "UTC time = %s" , buffer);
}
 
void *routine( void *arg)
{
     int i;
 
     for (i = 0; i < 2; i++) {
         print_time();
         sleep(1);
     }
     return NULL;
}
 
int main()
{
     int i;
     pthread_t tid;
 
     pthread_create(&tid, NULL, routine, NULL);
     routine(NULL);
     pthread_join(tid, NULL);
     return 0;
}

Output

?
1
2
3
4
UTC time = Fri Jan  2 12:43:08 2015
UTC time = Fri Jan  2 12:43:08 2015
UTC time = Fri Jan  2 12:43:09 2015
UTC time = Fri Jan  2 12:43:09 2015