巧用C的Time函數進行時間轉換

來源:互聯網
上載者:User

我們經常要遇到時間處理的問題,比如要開發一個schedule的功能,或根據修改時間來過濾檔案等。windows API提供了Get*Time()系列函數用於擷取目前時間,但是沒有提供進行時間轉換的,比如我們要得到距離目前時間2年4個月5天的時間,我們就得自己去計算了。但是這裡有個問題,如果被減的天數大於當前月份的天數,那麼天數就會變成負值。為瞭解決這個問題,我們就根據不同月份的天數來計算位移,同時做月和年的變化。不過這種方法很麻煩,因為每個月天數是不同的還需要考慮閏年和平年的問題。其實C的Time系列函數可以很好的解決這個問題,

1. 首先用TM結構進行需要的時間位移

2. 然後利用mktime這個函數將TM結構轉換到從1900.1.1開始的秒數值

3. 再利用localtime 把秒數轉換成TM結構

範例程式碼如下:

代碼

#include "stdafx.h"
#include <Windows.h>
#include <time.h>
#include <iostream>
using namespace std;

void OffsetDateTime(const struct tm* inST, struct tm* outST,
                    int dYears, int dMonths, int dDays, 
                    int dHours, int dMinutes, int dSeconds)
{
    if (inST != NULL && outST != NULL)
    {
          // 位移目前時間 
        outST->tm_year = inST->tm_year - dYears;
        outST->tm_mon  = inST->tm_mon  - dMonths;
        outST->tm_mday = inST->tm_mday - dDays;
        outST->tm_hour = inST->tm_hour - dHours;
        outST->tm_min  = inST->tm_min  - dMinutes;
        outST->tm_sec  = inST->tm_sec  - dSeconds;
        
        // 轉換到從1900.1.1開始的總秒數
        time_t newRawTime = mktime(outST);
        
        // 將秒數轉換成時間結構體
        outST = localtime(&newRawTime);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    time_t rawtime;
    struct tm * st;
    // 擷取本地目前時間
    time(&rawtime);
    st = localtime(&rawtime);
    cout << st->tm_year << "-" << st->tm_mon << "-" << st->tm_mday << endl;
    
    // 計算時間位移
    struct tm outst;
    OffsetDateTime(st, &outst, 2, 3, 20, 0, 0, 0);
    time_t newTime = mktime(&outst);

    cout << outst.tm_year << "-" << outst.tm_mon << "-" << outst.tm_mday << endl;
    cout << "rawTime: " << rawtime << endl << "newTime :" << newTime << endl;

    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.