Windows編程中幾種時間的相互轉換

來源:互聯網
上載者:User

  本地時間(LocalTime)轉UTC時間(Time_t格式)

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); // 注意strncpy與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); // 得到目前時間
newTime = localtime( &szClock ); // 把目前時間轉為tm結構體,從而可以得到年月日
char info[MAX_PATH] = {""};
char curTime[50] = {""};
//把目前時間組合成一個字串: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,"目前時間: time_t: %d , %s \r\n",szClock ,curTime);
printf(info);
//把組合成的yyyy-MM-dd hh:mm:ss字串通過mfc函數轉為time_t時間
long lcurtime = GetLongTimeByStrInC(curTime);
printf("通過c函數把目前時間: %s \n轉為:time_t: %d \r\n",curTime,lcurtime);
system("pause");
return 1;
}

  UTC時間(Time_t格式)轉本地時間(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("當前時間:%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;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.