Pergunta

Como faço para criar uma hora UTC em C para a data seguinte:

1 de julho de 2038

usando chamadas de função de padrão ANSI C (dado que o elemento tm_year da estrutura de TM não pode ser maior do que 137)?

Foi útil?

Solução

Você não. Os rolos de 32-bit ANSI C time_t mais em 2038. É como perguntar como você criar 23 de julho de 2003 em seu sistema COBOL de 2 dígitos anos.

Outras dicas

Outros notaram que a data especial que você dá como exemplo cai além do representável data máxima / hora por uma 32-bit time_t, muitas vezes referido como o ano de 2038 problema . Uma solução é usar um time_t de 64 bits, que alguns sistemas POSIX de 64 bits fazer (linux amd64) e mktime chamada.

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

int main(void)
{
        struct tm future;       /* as in future date */
        time_t t;

        future.tm_sec = 0;
        future.tm_min = 0;
        future.tm_hour = 0;
        future.tm_mday = 1;     /* 1st */
        future.tm_mon = 6;      /* July */
        future.tm_year = 2038 - 1900; /* 2038 in years since 1900 */
        future.tm_isdst = 0;          /* Daylight Saving not in affect (UTC) */
#ifdef _BSD_SOURCE
        future.tm_zone = "UTC";
#endif

        t = mktime( &future );
        if ( -1 == t ) {
                printf("Error converting 1 July 2038 to time_t time since Epoch\n");
                return EXIT_FAILURE;
        }

        printf("UTC time and date: %s\n", asctime( &future ) );

        return EXIT_SUCCESS;
}

Você pode tentar, fazendo uso de exemplo a seguir:

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


int main(void)
{
  struct tm *local;
  time_t t;

  t = time(NULL);
  local = localtime(&t);
  printf("Local time and date: %s\n", asctime(local));
  local = gmtime(&t);
  printf("UTC time and date: %s\n", asctime(local));

  return 0;
}

Deve dar-lhe, o resultado esperado.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top