Produzione di un timestamp UNIX fuori dalla data e ora passata in C

Produzione di un timestamp UNIX fuori dalla data e ora passata in C


Sto trasferendo un'app C da Solaris a RedHat e questa funzione non funziona molto bene su RedHat (e ho bisogno del tuo aiuto per determinare il motivo):


int toTimestamp (const char *InputDate, const char *DateFormat, time_t *lTimestamp){
struct tm tm;
if (NULL == strptime(InputDate, DateFormat, &tm)){
return FALSE;
}
*lTimestamp = mktime(&tm);
return TRUE;
}

Fondamentalmente, produce un timestamp UNIX di datetime passato come stringa, con il formato specificato.


char *effPaymentDate = NULL;
char *CohDueDate = NULL;
//...
effPaymentDate = PayRec->RecDate;//char RecDate[8+1];, value 20141005
CohDueDate = PayRec->DueDate;//char DueDate[8+1];, value 20140820
time_t currentDateUNIX;
time_t DueDateUNIX;
if (FALSE == toTimestamp(CohDueDate, "%Y%m%d", &DueDateUNIX) ||
FALSE == toTimestamp(effPaymentDate, "%Y%m%d", &currentDateUNIX)) {
return NULL;
}
//...

Tuttavia, non sembra funzionare correttamente (funziona bene per effPaymentDate, fornisce date errate per CohDueDate, ovvero l'anno 2543) - qualche idea sul perché?


Risposte:


TL;DR:


Devi inizializzare tm prima di passarlo alle API:


memset(&tm, 0, sizeof tm);

Perché?


strptime potrebbe fallire senza che tu te ne accorga:


$ man strptime


Quindi perché tm non è impostato su 0, alcuni campi possono contenere valori casuali.


Inoltre:


$ man mktime


È probabile che i valori casuali siano fuori intervallo e mktime cerca di normalizzarlo.
Ha fatto un buon lavoro, ma il year l'ha tradito!