Recently it was needed to convert UTC time string to local computer time string in C++ code. After analyzing several examples from stackoverflow and other resources I implemented this one. It is short application free from explicitely specified time zone. It is not extremely sophisticated at all. I am keeping it here mainly for my personal use, may be in future I will need to do it again, so I have working example to copy from and paste it somewhere. The code is below:
#include <stdio.h>
#include <sys/times.h>
#include <time.h>
#include <string.h> int main(int argc, char * argv[]) { if(argc<2) { printf("Specify UTI time in the followin format: YYYY-MM-DAY HH:MM:SS\n"); return -1; } char szBuffer[32]; struct tm tmstr; struct tm * tmlocal; time_t tslastutc; time_t tslastloc; memset(&tmstr, 0, sizeof(tm)); strptime(argv[1], "%Y-%m-%d %H:%M:%S", &tmstr); // convert argument to struct tm memset(&szBuffer, 0, sizeof(szBuffer)); strftime(szBuffer, sizeof(szBuffer), "%Y-%m-%d %H:%M:%S", &tmstr); // convert struct tm to string printf("UTC date and time: %s\n", szBuffer); tslastutc = timegm(&tmstr); // get UCT Unix time from argument string time tslastloc = mktime(&tmstr); // get local Unix time from argument string time tslastloc += tslastutc - tslastloc; tmlocal = localtime (&tslastloc); memset(&szBuffer, 0, sizeof(szBuffer)); strftime(szBuffer, sizeof(szBuffer), "%Y-%m-%d %H:%M:%S", tmlocal); // convert local struct tm to string printf("Local date and time: %s\n", szBuffer); return 0; }
Results:
# ./fromUTC “2018-2-19 23:01:00” UTC date and time: 2018-02-19 23:01:00 Local date and time: 2018-02-19 18:01:00 # ./fromUTC “2018-2-19”
|
It runs ok!