2016-04-26 29 views
0

私はCに新しく、strptime関数を試しています。これは文字列の時刻を構造体tmに変換します。変換後、私は正当な時を得ていない。すべて正常ですが、年は間違って表示されています(デフォルトの1900年)。strptimeはタイムゾーン形式指定子では機能しません

#include <stdio.h> 
#include <time.h> 
#include <string.h> 
#include <ctype.h> 

int main() 
{ 
    struct tm tm; 
    char *pszTemp = "Mon Apr 25 09:53:00 IST 2016"; 
    char szTempBuffer[256]; 

    memset(&tm, 0, sizeof(struct tm)); 
    memset(szTempBuffer, 0, sizeof(szTempBuffer)); 
    strptime(pszTemp, "%a %b %d %H:%M:%S %Z %Y", &tm); 
    strftime(szTempBuffer, sizeof(szTempBuffer), "%Y-%m-%d %H:%M:%S", &tm); 

    printf("Last Boot Time after parsed = %s\n", szTempBuffer); 

    return 0; 
} 

出力:1900年4月25日9時53分00秒

+1

['strptime'](http://man7.org/linux/man-pages/man3/strptime.3.html)が返すものを確認しましたか? NULLポインタを返さないようにするには? –

+0

'-Wall'オプションでコンパイルしようとしましたか? – LPs

+0

@LP:動作しませんでした。 –

答えて

1

あなたはtime.h

#define __USE_XOPEN 
#define _GNU_SOURCE 

#include <stdio.h> 
#include <time.h> 
#include <string.h> 
#include <ctype.h> 

int main() 
{ 
    struct tm tm; 
    char *pszTemp = "Mon Apr 25 09:53:00 IST 2016"; 
    char szTempBuffer[256]; 

    memset(&tm, 0, sizeof(struct tm)); 
    memset(szTempBuffer, 0, sizeof(szTempBuffer)); 
    strptime(pszTemp, "%a %b %d %H:%M:%S %Z %Y", &tm); 
    strftime(szTempBuffer, sizeof(szTempBuffer), "%Y-%m-%d %H:%M:%S", &tm); 

    printf("Last Boot Time after parsed = %s\n", szTempBuffer); 

    return 0; 
} 
を含めるようにする前に __USE_XOPEN_GNU_SOURCEを宣言するためにあなたが持っている time.hソースファイルに見ることができるように

gccコマンドに定義を追加することもできます。

gcc -Wall test.c -o test -D__USE_XOPEN -D_GNU_SOURCE 

EDIT

This historical SO postは、それらの定義についてのすべてに関する情報を提供します。

+1

なぜそれが必要なのか説明できますか?編集:ありがとう。 – 2501

+0

@ 2501 [この歴史的な投稿](http://stackoverflow.com/questions/5378778/what-does-d-xopen-source-do-mean)は、これらの定義についてのすべての情報を提供します。 – LPs

+0

動作しませんでした。同じ出力を得ました。 –

0

%Zは、strptimeに対してのみ機能し、strftimeに対しては機能しません。 %Zの後にstrptimeが読み込みを停止します。したがって、2016年は失われています。

http://linux.die.net/man/3/strptime

あなたがたglibcを使用している場合は、それが動作するはずです。

+0

%Zと2016の位置でちょっと遊んでみてください – kbnl83

関連する問題