2015-06-27 30 views
-1

這裏是我如何做到這一點在Linux中,但在Windows中我沒有strptime函數任何人都可以幫助我解決這個問題?如何在Windows中與C進行比較

#include <stdio.h> 
#include <time.h> 
#include <sys/time.h> 

time_t to_seconds(const char *date) 
{ 
    struct tm storage = {0, 0, 0, 0, 0, 0, 0, 0, 0}; 
    char  *p  = NULL; 
    time_t retval = 0; 

    p = (char *) strptime(date, "%d-%b-%Y", &storage); 
    if (p == NULL) 
    { 
     retval = 0; 
    } 
    else 
    { 
     retval = mktime(&storage); 
    } 
    return retval; 
} 

int main(int argc, char** argv) 
{ 
    time_t d1 = to_seconds("16-Jun-2015"); 
    time_t d2 = to_seconds("13-Jun-2015"); 
    if(d1 > d2) 
    { 
     printf("date 1 > date 2"); 
    } 
} 
+0

爲什麼投'(字符*)STRP ...'?另外,'strptime()'不是標準的。 –

+0

你是什麼意思? –

+0

我的意思是,當它可用時,不需要將'strptime()'強制轉換爲'char *',並且它不在Windows上,因爲它不是標準函數。爲什麼這種格式,你從哪裏得到日期?這是一個文件嗎? –

回答

0

我這個做功能,使用方便...

https://github.com/vforv/date-compare-C

+0

只有鏈接的答案不是SO的首選答案類型。至少你想在這裏粘貼代碼的相關部分以及解釋,爲什麼它會回答這個問題。 – alk

1

如果你碰巧使用的.Net,我建議:

1)使用Convert()DateTime.Parse()

示例:

string date = "01/08/2008"; 
DateTime dt = Convert.ToDateTime(date);  

2)使用DateTime.Compare()比較兩個日期時間值:

例:

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); 
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0); 
int result = DateTime.Compare(date1, date2); 
if (result < 0) 
    Console.WriteLine("is earlier than"); 
else if (result == 0) 
    Console.WriteLine("is the same time as";   
else 
    Console.WriteLine("is later than"; 
+0

我以前用過VB.NET,我知道用.NET很容易......但我現在正在學習C ...... :) –

+0

問題是關於C明確的。 – alk

相關問題