gpt4 book ai didi

c - 如何在 C 中获得不同时区的 Epoch 日期和时间?

转载 作者:太空宇宙 更新时间:2023-11-04 12:07:15 30 4
gpt4 key购买 nike

这是我用 C 编写的代码,我试图在其中获取当前纪元的日期和时间。不过,好像不对?我在这里的逻辑中缺少什么?这是遗留代码,我不确定为什么我们需要调整偏移量。

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

#define SECS_IN_DAY (60 * 60 * 24)
static void GetEpochs()
{
const int SECS_IN_MINUTE = 60;
const int MIN_IN_HOUR = 60;
const int SECS_IN_HOUR = SECS_IN_MINUTE * MIN_IN_HOUR;


int offset; /* difference (+/-) between local and UTC time in seconds */
time_t currentTime = time(NULL); /* current time in seconds */
time_t adjustedTime; /* current time adjusted for timezone */

struct tm* locTime = localtime(&currentTime);
int localHour = locTime->tm_hour;
int localMin = locTime->tm_min;

struct tm* gmTime = gmtime(&currentTime);
int gmHour = gmTime->tm_hour;
int gmMin = gmTime->tm_min;

/* create difference between local and gm time in (+/-) seconds */
offset = ((localHour * SECS_IN_HOUR) + (localMin * SECS_IN_MINUTE)) - ((gmHour * SECS_IN_HOUR) + (gmMin * SECS_IN_MINUTE));

/* adjust for wrapping over/under a day */


if (offset > SECS_IN_DAY/2)
offset = offset - SECS_IN_DAY;
else if (offset < -(SECS_IN_DAY/2))
offset = offset + SECS_IN_DAY;

/* Create the adjusted time */
adjustedTime = currentTime + offset;


printf("Epoch Hour = %ld\r\n",adjustedTime/((15 * 60)));

printf("Epoch Day = %ld\r\n",adjustedTime/(((60 * 60 * 24))));
}

void main()
{
GetEpochs();

}

最佳答案

用于 time.h header 中定义的各种函数的时区由 TZ 环境变量确定。

在不触及 TZ 环境的情况下使用 localtime() 函数,默认情况下将使用您操作系统的时区。更准确地说,它将使用您从 UNIX 系统上的系统时区目录(即 /usr/share/zoneinfo矿)。我个人不知道其他操作系统的功能。

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

int main(void)
{
// print date and time in your local timezone
struct tm* t1 = localtime( &(time_t){time(NULL)} );
printf("%s", asctime(t1));

// print date and time in UTC
setenv("TZ", "UTC", 1);
struct tm* t2 = localtime( &(time_t){time(NULL)} );
printf("%s", asctime(t2));

// print date and time reading from the timezone file
setenv("TZ", ":Europe/London", 1);
struct tm* t3 = localtime( &(time_t){time(NULL)} );
printf("%s", asctime(t3));

return 0;
}

上述程序的输出将如下所示:

Tue May  8 09:49:42 2018
Tue May 8 07:49:42 2018
Tue May 8 08:49:42 2018

我在第三个例子中谈到的文件是相对于系统时区目录的,在本例中为/usr/share/zoneinfo/Europe/London

您可以在 tzset() manpage 中阅读有关 TZ env 以及调整它的方法的更多信息.

关于c - 如何在 C 中获得不同时区的 Epoch 日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50227212/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com