web-dev-qa-db-ja.com

Cプログラムで日付と時刻の値を取得する方法は?

私はこのようなものを持っています:

char *current_day, *current_time;
system("date +%F");
system("date +%T");

現在の日時を標準出力に出力しますが、この出力を取得するか、current_dayおよびcurrent_time変数に割り当てて、後でこれらの値で処理できるようにします。

current_day ==> current day
current_time ==> current time

今考えられる唯一の解決策は、出力を何らかのファイルに送信し、ファイルを読み取ってから、日時の値をcurrent_dayおよびcurrent_timeに割り当てることです。しかし、これは良い方法ではないと思います。他の短くてエレガントな方法はありますか?

52

time() および localtime() を使用して時間を取得します。

#include <time.h>

time_t t = time(NULL);
struct tm tm = *localtime(&t);

printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
126
Adam Rosenfield
time_t rawtime;   
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );

strftime を使用して、時刻を文字列にフォーマットすることもできます。

17
Martin Beckett

strftime(C89)

Martin 言及 、ここに例があります:

main.c

#include <assert.h>
#include <stdio.h>
#include <time.h>

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    assert(strftime(s, sizeof(s), "%c", tm));
    printf("%s\n", s);
    return 0;
}

GitHubアップストリーム

コンパイルして実行:

gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out

サンプル出力:

Thu Apr 14 22:39:03 2016

%c指定子は、ctimeと同じ形式を生成します。

この関数の利点の1つは、書き込まれたバイト数を返すことです。これにより、生成された文字列が長すぎる場合のエラー制御が改善されます。

戻り値

  Provided  that  the  result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s.  If the length of the result string (including the terminating null byte) would exceed max bytes, then
   strftime() returns 0, and the contents of the array are undefined.

  Note that the return value 0 does not necessarily indicate an error.  For example, in many locales %p yields an empty string.  An empty format string will likewise yield an empty string.

asctimeおよびctime(C89)

asctimeは、struct tmをフォーマットする便利な方法です。

main.c

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s", asctime(tm));
    return 0;
}

サンプル出力:

Wed Jun 10 16:10:32 2015

また、標準では次のショートカットと呼ばれるctime()もあります。

asctime(localtime())

by Jonathan Leffler で述べたように、この形式にはタイムゾーン情報がないという欠点があります。

POSIX 7 は、これらの関数を「廃止」としてマークしたため、将来のバージョンで削除される可能性があります。

標準の開発者は、バッファオーバーフローの可能性のためにasctime()がISO C標準に含まれている場合でも、asctime()およびasctime_r()関数を廃止とマークすることにしました。 ISO C標準は、これらの問題を回避するために使用できるstrftime()関数も提供します。

この質問のC++バージョン: C++で現在の時刻と日付を取得する方法

Ubuntu 16.04でテスト済み。

Timespecには年内の日付が組み込まれています。

http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html

#include <time.h>
int get_day_of_year(){
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    return tm.tm_yday;
}`
1
RooterTooter

上記の回答はCRTの優れた回答ですが、必要に応じてWin32ソリューションも使用できます。ほとんど同じですが、Windows用にプログラミングしている場合はIMOだけでなく、APIを使用することもできます(実際にWindowsでプログラミングしている場合は何でも)

char* arrDayNames[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Jeez I hope this works, I haven't done this in ages and it's hard without a compiler..
SYSTEMTIME st;
GetLocalTime(&st); // Alternatively use GetSystemTime for the UTC version of the time
printf("The current date and time are: %d/%d/%d %d:%d:%d:%d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
printf("The day is: %s", arrDayNames[st.wDayOfWeek]);

とにかく、これはあなたのWindowsソリューションです。いつかあなたの役に立つことを願っています!

1
Ori Osherov

答えを広げる by Ori Osherov

WinAPI を使用して日付と時刻を取得できます。このメソッドはWindowsに固有ですが、Windowsのみをターゲットにしている場合、または既にWinAPIを使用している場合、これは間違いなく可能です1

SYSTEMTIMEstructを使用して、時刻と日付の両方を取得できます。また、2つの関数(GetLocalTime()またはGetSystemTime()のいずれか)のいずれかを呼び出して、structを埋める必要があります。

GetLocalTime()は、あなたのタイムゾーンに固有の日時を提供します

GetSystemTime()UTC で時刻と日付を提供します= =

SYSTEMTIMEstructには次のメンバーがあります。

wYearwMonthwDayOfWeekwDaywHourwMinutewSecond、およびwMilliseconds

その後、通常の方法でstructにアクセスするだけです


実際のコード例:

#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)

int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)

    SYSTEMTIME t; // Declare SYSTEMTIME struct

    GetLocalTime(&t); // Fill out the struct so that it can be used

    // Use GetSystemTime(&t) to get UTC time 

    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order

    return 0;
}

(単純化および明確化のためにコード化された、 より良いフォーマット化されたメソッドの元の答え を参照)

出力は次のようになります。

Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572

便利なリファレンス:

すべてのWinAPIドキュメント(ほとんどの場合、上記にリストされています):

Zetcodeによるこのテーマに関する非常に優れた初心者向けチュートリアル:

Codeprojectでの日時の簡単な操作:


1:Ori Osherovの回答( "Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17")のコメントで述べたように、OPはWindowsを使用してnotですが、この質問にはプラットフォーム固有のタグがありません(またはそれは答えがその特定のシステムにあるべきであることをどこでも言及していますか)、そしてグーグルが「cで時間を取得する」両方の答えがここに属している場合のトップの結果の1つです彼らに役立つでしょう。

0
Simon