Skip to main content
FPicc.1
Associate III
February 28, 2024
Question

How to transform date and time received to timestamp

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.

6 replies

Tesla DeLorean
Guru
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/

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
Tesla DeLorean
Guru
February 28, 2024

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 (See Profile) Up vote any posts that you find helpful, it shows what's working..
Andrew Neil
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

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
FPicc.1
FPicc.1Author
Associate III
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

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

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.