/*********************************************************************************
|
* 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;
|
}
|