Skip to content

Instantly share code, notes, and snippets.

@igrr
Last active April 11, 2023 09:44
Show Gist options
  • Select an option

  • Save igrr/3f322b773eda81c713615a2337f37b94 to your computer and use it in GitHub Desktop.

Select an option

Save igrr/3f322b773eda81c713615a2337f37b94 to your computer and use it in GitHub Desktop.

Revisions

  1. igrr revised this gist Mar 17, 2022. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions get_set_time_example.c
    Original file line number Diff line number Diff line change
    @@ -52,6 +52,7 @@ static void get_time(void)
    // 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
  2. igrr created this gist Mar 17, 2022.
    59 changes: 59 additions & 0 deletions get_set_time_example.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    #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
    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));
    }