Skip to main content
Visitor II
February 28, 2024
Question

How to transform date and time received to timestamp

  • February 28, 2024
  • 2 replies
  • 2962 views

Hi all,

I am receiving date and time by CAN for my application, and not using the RTC functionality because I couldn't get it to work with LoRa.

Basically I receive day and month separately, and declare the year as a int. Same thing for the time, I receive hour, minutes and seconds separately.

Is there a way that I can join them into a timestamp variable?

    This topic has been closed for replies.

    2 replies

    Graduate II
    February 28, 2024

    >>Is there a way that I can join them into a timestamp variable?

    Surely a relatively common math problem? Depends on the epoch you want to use and the resolution of time. You could look in the functions provided in time.h ?

    mktime() ?

    https://cplusplus.com/reference/ctime/mktime/

    Graduate II
    February 28, 2024

    Time in seconds could then be counted off in Systick_Handler() after counting 1000 milli-seconds in the 1 KHz ticker.

    Super User
    February 28, 2024

    @FPicc.1 wrote:

    Is there a way that I can join them into a timestamp variable?


    That gets complicated with having to cope with leap years, DST, etc - are you sure you really want to do that?

    If you really must, look at mktime

    https://en.cppreference.com/w/c/chrono/mktime

    FPicc.1Author
    Visitor II
    February 28, 2024

    Saw this code at: https://os.mbed.com/questions/79859/How-can-I-convert-input-Date-Time-to-Uni/

     

    time_t asUnixTime(int year, int mon, int mday, int hour, int min, int sec) {
     struct tm t;
     t.tm_year = year - 1900;
     t.tm_mon = mon - 1; // convert to 0 based month
     t.tm_mday = mday;
     t.tm_hour = hour;
     t.tm_min = min;
     t.tm_sec = sec;
     t.tm_isdst = -1; // Is Daylight saving time on? 1 = yes, 0 = no, -1 = unknown
     
     return mktime(&t); // returns seconds elapsed since January 1, 1970 (begin of the Epoch)
    }

     Could it work? Will test it later

    Super User
    February 28, 2024

    Sure. That's using mktime - as I mentioned.

    You'll have to check if it's implemented in the standard STM32 GCC release.

    You'll still have to beware of DST ...