time.hのtm構造体を使用する
#include <stdio.h> #include <time.h> int main() { long int seconds_since_epoch; struct tm current_time, *time_ptr; int hour, minute, second, day, month, year; seconds_since_epoch = time(0); printf("time() - エポックからの通算秒数: %ld\n", seconds_since_epoch); time_ptr = ¤t_time; localtime_r(&seconds_since_epoch, time_ptr); hour = current_time.tm_hour; minute = time_ptr->tm_min; second = *((int *) time_ptr); printf("現在の時間は: %02d:%02d:%02d\n", hour, minute, second); return 0; }
$ ./a.out
time() – エポックからの通算秒数: 1707729486
現在の時間は: 03:18:06
$ ./a.out
time() – エポックからの通算秒数: 1707729492
現在の時間は: 03:18:12
#include <stdio.h> #include <time.h> void dump_time_struct_bytes(struct tm *time_ptr, int size){ int i; unsigned char *raw_ptr; printf("0x%08x にある構造体の内容\n", time_ptr); raw_ptr = (unsigned char *) time_ptr; for(i=0; i<size; i++){ printf("%02x ", raw_ptr[i]); if(i%16 == 15) printf("\n"); } printf("\n"); } int main() { long int seconds_since_epoch; struct tm current_time, *time_ptr; int hour, minute, second, i, *int_ptr; seconds_since_epoch = time(0); printf("time() - エポックからの通算秒数: %ld\n", seconds_since_epoch); time_ptr = ¤t_time; localtime_r(&seconds_since_epoch, time_ptr); hour = current_time.tm_hour; minute = time_ptr->tm_min; second = *((int *) time_ptr); printf("現在の時間は: %02d:%02d:%02d\n", hour, minute, second); dump_time_struct_bytes(time_ptr, sizeof(struct tm)); minute = hour = 0; int_ptr = (int *) time_ptr; for(i=0; i < 3; i++) { printf("int ptr @ 0x08x : %d\n", int_ptr, *int_ptr); int_ptr++; } return 0; }
$ ./a.out
time() – エポックからの通算秒数: 1707730079
現在の時間は: 03:27:59
0xf089a030 にある構造体の内容
3b 00 00 00 1b 00 00 00 03 00 00 00 0c 00 00 00
01 00 00 00 7c 00 00 00 01 00 00 00 2a 00 00 00
00 00 00 00 ff ff 00 00 a0 ab ff ff ff ff ff ff
00 a9 5d d4 aa aa 00 00
int ptr @ 0x08x : -259416016
int ptr @ 0x08x : -259416012
int ptr @ 0x08x : -259416008