C言語での日付形式の変換方法は何ですか?
C言語では、日付の形式を変換するためにstrftime関数を使用することができます。strftime関数の原型は以下の通りです:
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
パラメータの説明:
- str:結果を保存する文字列のポインタ。
- maxsize:str型の文字列の最大長。
- フォーマット:文字列の形式を変換します。
- timeptrは、日付と時刻を表すtm構造体へのポインタを指し、変換する日付と時刻を示しています。
現在の日付と時間を特定の形式の文字列に変換する例を次に示します:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("Formatted date and time: %s\n", buffer);
return 0;
}
結果を出力する:
Formatted date and time: 2022-01-01 12:34:56
strftime関数の第3引数では、異なるフォーマット指定子を使用して異なる日付および時刻のフォーマットを定義できます。たとえば、%Yは4桁の年、%mは2桁の月、%dは2桁の日、%Hは24時間制の時、%Mは分、%Sは秒を表します。詳細なフォーマット指定子については、C言語の関連ドキュメントを参照してください。