Skip to content

Instantly share code, notes, and snippets.

@hanetzer
Forked from jonforums/xp_gmtime_r.c
Created June 8, 2014 06:12
Show Gist options
  • Save hanetzer/02ffc4e0483a364c4ffb to your computer and use it in GitHub Desktop.
Save hanetzer/02ffc4e0483a364c4ffb to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <time.h>
#if defined(__MINGW64_VERSION_MAJOR)
/* XXX why isn't this in sec_api/time_s.h? */
# if defined(_USE_32BIT_TIME_T)
# define gmtime_s _gmtime32_s
# else
# define gmtime_s _gmtime64_s
# endif
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
# define BUILDING_WITH_MINGW32
# define gmtime_r(tp, tm) (gmtime((tp)))
# define localtime_r(tp, tm) (localtime((tp)))
#endif
#if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
# define gmtime_r(tp, tm) ((gmtime_s((tm), (tp)) == 0) ? (tm) : NULL)
# define localtime_r(tp, tm) ((localtime_s((tm), (tp)) == 0) ? (tm) : NULL)
#endif
int
main(int argc, char *argv[])
{
time_t rawtime;
struct tm utc_tm, local_tm, tmp_tm, *my_utc_tm, *my_local_tm;
char buffer[1024] = "";
time(&rawtime);
my_utc_tm = gmtime_r(&rawtime, &utc_tm);
#ifdef BUILDING_WITH_MINGW32
/* save the *utc_tm so it doesn't get clobbered */
memcpy(&tmp_tm, my_utc_tm, sizeof(struct tm));
my_utc_tm = &tmp_tm;
#endif
my_local_tm = localtime_r(&rawtime, &local_tm);
if (strftime(buffer, sizeof(buffer),
"UTC: %A, %B %d, %Y %H:%M", my_utc_tm))
puts(buffer);
if (strftime(buffer, sizeof(buffer),
"Local: %A, %B %d, %Y %H:%M %z", my_local_tm))
puts(buffer);
return 0;
}
/* vim: set ts=2 sts=2 sw=2 et: */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment