Local time (LocalTime) to UTC time (Time_t format)
View Code
# Include <time. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <windows. h>
Long GetLongTimeByStrInC (char * strTime)
{
If (strTime = NULL)
Return 0;
Char years [5] = {""}, month [3] = {""}, day [3] = {""},\
Hour [3] = {""}, minute [3] = {""}, second [3] = {""};
LstrcpynA (years, strTime, 5); // note the difference between strncpy and lstrcpyn
LstrcpynA (month, strTime + 5, 3 );
LstrcpynA (day, strTime + 8, 3 );
LstrcpynA (hour, strTime + 11, 3 );
LstrcpynA (minute, strTime + 14, 3 );
LstrcpynA (second, strTime + 17, 3 );
Tm newTime;
NewTime. tm_year = atoi (years)-1900;
NewTime. tm_mon = atoi (month)-1;
NewTime. tm_mday = atoi (day );
NewTime. tm_hour = atoi (hour );
NewTime. tm_min = atoi (minute );
NewTime. tm_sec = atoi (second );
Return mktime (& newTime );
}
Int main (void)
{
Tm * newTime;
Time_t szClock = time (NULL); // get the current time
NewTime = localtime (& szClock); // convert the current time to the tm struct to get the year, month, and day.
Char info [MAX_PATH] = {""};
Char curTime [50] = {""};
// Combine the current time into a string: yyyy-MM-dd hh: mm: ss
Sprintf (curTime, "% 04d-% 02d-% 02d % 02d: % 02d: % 02d", newTime-> tm_year + 1900, newTime-> tm_mon + 1, newTime-> tm_mday ,\
NewTime-> tm_hour, newTime-> tm_min, newTime-> tm_sec );
Sprintf (info, "Current Time: time_t: % d, % s \ r \ n", szClock, curTime );
Printf (info );
// Convert the converted yyyy-MM-dd hh: mm: ss string to time_t time using the mfc function.
Long lcurtime = GetLongTimeByStrInC (curTime );
Printf ("convert current time: % s \ n to: time_t: % d \ r \ n", curTime, lcurtime through the c function );
System ("pause ");
Return 1;
}
UTC time (Time_t format) to local time (LocalTime)
View Code
# Include <time. h>
# Include <Windows. h>
Int _ tmain (int argc, _ TCHAR * argv [])
{
Time_t UnixTime = 1330354352;
Tm ToLocalTime;
ZeroMemory (& ToLocalTime, sizeof (tm ));
Localtime_s (& ToLocalTime, & UnixTime );
Printf ("time before: % 04d-% 02d-% 02d % 02d: % 02d: % 02d \ n", ToLocalTime. tm_year + 1900, ToLocalTime. tm_mon + 1, ToLocalTime. tm_mday,
ToLocalTime. tm_hour, ToLocalTime. tm_min, ToLocalTime. tm_sec );
System ("pause ");
Return 0;
}