APUE course source code
guowenxue
2 days ago 9c22371ef5059a2e46226ee90a0667ffad65b574
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  time.c
 *    Description:  This file is print current time
 *
 *        Version:  1.0.0(10/15/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/15/2025 04:54:04 PM"
 *
 ********************************************************************************/
 
#include <stdio.h>
#include <time.h>
 
/* Print struct tm information with weekday and timezone */
void print_tm_info(const char *label, struct tm *t)
{
    const char *weekday[] = {
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };
 
    printf("%s: %d-%02d-%02d %02d:%02d:%02d\n",
           label,
           t->tm_year + 1900,
           t->tm_mon + 1,
           t->tm_mday,
           t->tm_hour,
           t->tm_min,
           t->tm_sec);
 
    printf("  Weekday: %s\n", weekday[t->tm_wday]);
 
    if (t->tm_zone != NULL)
    {
        printf("  Timezone: %s\n", t->tm_zone);
    }
    else
    {
        printf("  Timezone: UTC\n");
    }
 
    printf("  tm_yday = %d\n", t->tm_yday);
}
 
int main(void)
{
    time_t t;
    struct tm *tm_ptr;
    struct tm tm_local_r;
    struct tm tm_gmt_r;
 
    /* 获取当前时间戳 */
    t = time(NULL);
    printf("Epoch time: %ld\n\n", (long)t);
 
    /* localtime (非线程安全) */
    tm_ptr = localtime(&t);
    if (tm_ptr != NULL)
    {
        print_tm_info("Local time (localtime)", tm_ptr);
    }
 
    /* localtime_r (线程安全) */
    if (localtime_r(&t, &tm_local_r) != NULL)
    {
        print_tm_info("Local time (localtime_r)", &tm_local_r);
    }
 
    /* gmtime (非线程安全) */
    tm_ptr = gmtime(&t);
    if (tm_ptr != NULL)
    {
        print_tm_info("UTC time (gmtime)", tm_ptr);
    }
 
    /* gmtime_r (线程安全) */
    if (gmtime_r(&t, &tm_gmt_r) != NULL)
    {
        print_tm_info("UTC time (gmtime_r)", &tm_gmt_r);
    }
 
    return 0;
}