Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Windows 綜合教學 >> Windows 技巧

UNIX C 日期時間計算函式:求指定日期前後任意秒數對應日期、時間與星期

編輯:Windows 技巧

功能簡介

計費程式常需計算某日期時間前後一段秒數對應的日期、時間及星期。UNIX C 標準庫未提供此功能,筆者設計 GetDateTime 函式解決此需求。

參數說明

  • s:輸入日期時間字串,格式 YYYYMMDDhhmmss(如 20010602183004)。
  • bill_long:時間長度(秒),負數表往前推。
  • d_str:輸出日期字串,格式 YYYYMMDD。
  • t_str:輸出時間字串,格式 hhmmss。
  • 回傳值:星期(0=週日,1-6=週一至六)。

完整實作碼

int GetDateTime(char *s, long int bill_long, char *d_str, char *t_str) {
    time_t timer, tim;
    struct tm tb, *tb1;
    int year_off = 1900, mon_off = 1;
    char s1[20];

    if (strlen(s) != 14) return -1;

    strncpy(s1, s, 4); s1[4] = '\0'; tb.tm_year = atoi(s1);
    strncpy(s1, s+4, 2); s1[2] = '\0'; tb.tm_mon = atoi(s1);
    strncpy(s1, s+6, 2); s1[2] = '\0'; tb.tm_mday = atoi(s1);
    if (tb.tm_year==0 || tb.tm_mon==0 || tb.tm_mday==0) return -1;
    strncpy(s1, s+8, 2); s1[2] = '\0'; tb.tm_hour = atoi(s1);
    strncpy(s1, s+10, 2); s1[2] = '\0'; tb.tm_min = atoi(s1);
    strncpy(s1, s+12, 2); s1[2] = '\0'; tb.tm_sec = atoi(s1);

    tb.tm_year -= year_off;
    tb.tm_mon -= mon_off;
    tb.tm_isdst = 0;

    tim = mktime(&tb);
    tim -= bill_long;
    tb1 = localtime(&tim);

    sprintf(d_str, "%04d%02d%02d", 1900+tb1->tm_year, tb1->tm_mon+1, tb1->tm_mday);
    sprintf(t_str, "%02d%02d%02d", tb1->tm_hour, tb1->tm_min, tb1->tm_sec);
    return (tb1->tm_wday);
}

應用價值

函式不僅計算前後任意秒數的日期時間,並直接給出星期,方便程式設計、費用計算與核對,可直接引用。

Copyright © Windows教程網 All Rights Reserved