challenge ミリ秒まで含んだ時刻文字列

YYYY年mm月dd日HH時MM分SS.xxx秒なら、「YYYYmmddHHMMSS.xxx」のようにミリ秒まで含んだ文字列を返すプログラムを書いてください。

Posted feedbacks - C

WindowsAPIではGetLocalTime()関数を使うとミリ秒単位の時刻が取得できます。
ただし、クロックの分解能(精度)は15~16ミリ秒ほどのようです。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>
#include <windows.h>

int main(int argc, char **argv)
{
    SYSTEMTIME    st;
    GetLocalTime(&st);
    printf("%04d%02d%02d%02d%02d%02d.%03d\n",
        st.wYear, st.wMonth,  st.wDay,
        st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
    return 0;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <sys/time.h>
#include <stdio.h>
int
main(void)
{
    struct timeval t;
    time_t c;
    struct tm r;

    gettimeofday(&t, NULL);
    c = t.tv_sec;
    localtime_r(&c, &r);
    printf("%04d%02d%02d%02d%02d%02d.%03d\n", r.tm_year + 1900, r.tm_mon + 1, r.tm_mday, r.tm_hour, r.tm_min, r.tm_sec, (int)(t.tv_usec / 1000));
    return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...