如何在C中获得大纪元日和时间甚至不同的时区?

时间:2018-05-08 06:26:33

标签: c linux

这是我在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();

}

1 个答案:

答案 0 :(得分:0)

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

使用localtime()功能而不触及TZ env,默认情况下会使用您的操作系统的时区。更确切地说,它将使用您从UNIX系统上的系统时区目录(/etc/localtime上的/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

我在第三个例子中讨论的文件是相对于系统时区目录,在这种情况下是TZ

您可以在tzset() manpage中详细了解[m,n] = size(object); area = m*n; x = [1:n]; y = [1:m]; [y,x] = meshgrid(x,y); z = zeros(size(x)); for i = 1:m, for j = 1:n, z = z + object(i,j)*exp(-((x-i).*(x-i) + (y-j).*(y-j))); end end z = z/area; env及其调整方式。