0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C 言語で現在時刻を取得する

Posted at

概要

C 言語で現在時刻を取得し、エポック秒から時間、分などの表記に変換する方法をメモ(毎回忘れるので🙃)。

方法

コレ↓

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>

int main(){
    struct timespec ts = (struct timespec){0};
    struct tm       lt = (struct tm){0};

    if(clock_gettime(CLOCK_REALTIME, &ts) == -1){
        fprintf(stderr, "clocl_gettime() failed with errno %d, line %d, file %s\n", errno, __LINE__, __FILE__);
        return -1;
    }

    memcpy(&lt, localtime(&(ts.tv_sec)), sizeof(struct tm));

    printf("Current time: %d/%d/%d, %d:%d:%d\n", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec);

    return 0;
}

スレッドセーフ版

localtime() はスレッドアンセーフとのこと。
localtime_r() というスレッドセーフ版を使うと↓のカンジ。

   struct tm newtime;
   time_t ltime;
   char buf[50];

   ltime=time(&ltime);
   localtime_r(&ltime, &newtime);
   printf("The date and time is %s", asctime_r(&newtime, buf));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?