Last active
April 11, 2023 09:44
-
-
Save igrr/3f322b773eda81c713615a2337f37b94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
#include <sys/time.h> | |
#include <unistd.h> | |
static void set_time(void); | |
static void get_time(void); | |
void app_main(void) | |
{ | |
set_time(); | |
while (1) { | |
get_time(); | |
sleep(1); | |
} | |
} | |
static void set_time(void) | |
{ | |
// Prepare the broken-down time. | |
// See https://en.cppreference.com/w/c/chrono/tm | |
struct tm initial_time = { | |
.tm_year = 2022 - 1900, | |
.tm_mon = 3 - 1, | |
.tm_mday = 17 - 1, | |
.tm_hour = 21, | |
.tm_min = 35, | |
.tm_sec = 0 | |
}; | |
// Convert to Unix time. | |
// See https://en.cppreference.com/w/c/chrono/mktime | |
time_t initial_unix_time = mktime(&initial_time); | |
// Convert to 'struct timeval' | |
struct timeval initial_timeval = { | |
.tv_sec = initial_unix_time, | |
.tv_usec = 0 | |
}; | |
// Set system time. | |
// See https://linux.die.net/man/2/settimeofday | |
int err = settimeofday(&initial_timeval, NULL); | |
assert(err == 0); | |
printf("Time set to: %s", asctime(&initial_time)); | |
} | |
static void get_time(void) | |
{ | |
// Get current time as 'struct timeval'. | |
// See https://linux.die.net/man/2/gettimeofday | |
struct timeval new_timeval; | |
int err = gettimeofday(&new_timeval, NULL); | |
assert(err == 0); | |
// Extract Unix time | |
time_t new_unix_time = new_timeval.tv_sec; | |
// Convert to broken-down time | |
// See https://en.cppreference.com/w/c/chrono/localtime | |
struct tm new_time; | |
localtime_r(&new_unix_time, &new_time); | |
// 'new_time' now contains the current time components | |
printf("Current time: %s", asctime(&new_time)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment