C言語 struct tm構造体を書式付き文字列に変換 - time.h - [ strftime ]

2008.12.05 Friday | by LRESULT


struct tm構造体を書式付き文字列に変換するには、strftime()を使います。


strftime
書式 size_t strftime( char *s,
                     size_t maxsize,
                     const char *format,
                     const struct tm *stm )
機能 struct tm構造体を書式付き文字列に変換
引数 char *s : 変換した文字列の格納先
size_t maxsize : 文字列の最大バイト数
const char *format : 書式文字列
const struct tm *stm : 変換元のstruct tm構造体
戻り値 変換した文字のバイト数を返します。



書式文字列
%Y : 西暦での年数
%y : 西暦での下2桁の年数
%m : 月数[01〜12]
%B : 月の名称
%b : 月の略称
%d : 日付[01〜31]
%x : 日付(年月日)
%c : 日付(年月日)と時刻
%j : 経過日数
曜日 %w : 曜日[0〜6](0が日曜日)
%W : 経過した週[00〜53](最初が月曜日)
%A : 曜日の名称
%a : 曜日の略称
%H : 時[00〜23]
%I : 時[00〜12]
%p : 午前/午後の文字列
%M : 分[00〜59]
%S : 秒[00〜61]
%X : 時刻(00:00:00)
その他 %% : %(パーセント記号)を表示





サンプルコード
現在の年月日と曜日、時刻をstruct tm構造体から
文字列に変換して表示してみます。
#include <stdio.h>
#include <time.h>
#include <locale.h>

int main(void)
{
  struct tm *stm;
  time_t tim;
  char s[100];

  setlocale( LC_ALL, "jpn" );

  time( &tim );
  stm = localtime( &tim );

  strftime( s, 100, "%Y年%m月%d日(%A) %H時%M分%S秒¥n", stm );
  puts( s );

  return 0;
}



結果
2008年12月5日(金曜日) 20時23分52秒
と、いうように表示されます。

setlocale()で日本語の地域にしている為、
%Aでの曜日表示は、日本語になります。

カテゴリ:C言語 time.h | 23:00 | comments(1) | trackbacks(0) | -


コメント

管理者の承認待ちコメントです。

| - | 2011/08/27 11:28 AM |

コメントする











この記事のトラックバックURL

トラックバック機能は終了しました。

トラックバック