cancel
Showing results for 
Search instead for 
Did you mean: 

How to transform date and time received to timestamp

FPicc.1
Associate III

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?

6 REPLIES 6

>>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/

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Andrew Neil
Evangelist III

@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

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

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

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

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 ...

in the standard STM32 GCC release

That's in the newlib library for ARM & ST toolchains and proprietary libraries for IAR, Keil etc.