Created
May 10, 2012 21:25
-
-
Save mattiasrunge/2656005 to your computer and use it in GitHub Desktop.
Get UTC epoch timestamp function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
#include <string.h> | |
/** | |
* This function returns a UTC epoch timestamp based on | |
* the supplied time information. | |
* | |
* @param [in] second Seconds [0-59] | |
* @param [in] minute Minutes [0-59] | |
* @param [in] hour Hours [0-23] | |
* @param [in] date Day of month [1-31] | |
* @param [in] month Month [1-12]. | |
* @param [in] year Years [1970-2335] | |
* | |
* @retval timestamp Epoch timestamp in UTC. | |
*/ | |
time_t utctimestamp(int second, int minute, int hour, int date, int month, int year) | |
{ | |
struct tm* pLocalTm = NULL; | |
struct tm wantedTm; | |
time_t epoch = 0; | |
/* Initialize variables */ | |
memset(&wantedTm, 0, sizeof(wantedTm)); | |
/* Set up time structure */ | |
wantedTm.tm_sec = second; | |
wantedTm.tm_min = minute; | |
wantedTm.tm_hour = hour; | |
wantedTm.tm_mday = date; | |
wantedTm.tm_mon = month - 1; | |
wantedTm.tm_year = year - 1900; | |
wantedTm.tm_isdst = -1; | |
/* Get the timestamp */ | |
epoch = mktime(&wantedTm); | |
/* Get local time information */ | |
pLocalTm = localtime(&epoch); | |
/* Adjust epoch to UTC */ | |
epoch += pLocalTm->tm_gmtoff; | |
/* Return timestamp */ | |
return epoch; | |
} | |
int main(int argc, char **argv) | |
{ | |
printf("Test #1> 1970-01-01 00:00:00 UTC : %lu, %s\n", (unsigned long)utctimestamp(00, 00, 00, 01, 01, 1970), utctimestamp(00, 00, 00, 01, 01, 1970) == 0 ? "PASS" : "FAIL"); | |
printf("Test #2> 2012-05-10 21:04:33 UTC : %lu, %s\n", (unsigned long)utctimestamp(33, 04, 21, 10, 05, 2012), utctimestamp(33, 04, 21, 10, 05, 2012) == 1336683873 ? "PASS" : "FAIL"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment