-2

I am having a bit of a brainfart and having trouble changing ISO timestamp into seconds in c++.

The current timestamp is ISO standard in single string for example 202207032201, 2022 July 3 22:01h and for the time being I took this as an integer and placed it in an x-axis of a plot and obviously this does not work well because days and time do not go up to 100 and I am getting large gaps in the x-axis.

The timestamp is an integer type and read from the filename/fileheader and I cannot do a epoch conversion normally.

I don't remember how to convert this type of timestamp into seconds/minutes to a reference time.

Can someone remind me how to do this?

Thanks.

Sj L
  • 41
  • 5

1 Answers1

0

To convert an ISO standard date string to a Unix Timestamp you need to use strptime to parse the string to a tm structure and mktime which converts a tm structure to a Unix Timestamp.

Example Code:

struct tm myTm;
const char *date = "202207032201, 2022 July 3 22:01h";
const char *format = "%Y%m%d%H%M,";

// convert string to struct tm
char *guard = strptime(date, format, &myTm);

// convert struct tm to timestamp
unsigned long localTime = mktime(&myTm);
unsigned long utcTime = mktime(&myTm) - myTm.tm_gmtoff;

printf("\n localTime %lu", localTime);
printf("\n utcTime %lu", utcTime);

As always with time functions verify which local time your device is configured to and which functions are influenced by it.

Falital
  • 177
  • 5
  • I remember there was a way to convert from int to time format. In your example, I don't see how *date and *format are being used or converted. – Sj L Aug 29 '22 at 08:40
  • @SjL Sorry I forgot to copy the strptime call in my example code now it is fixed. – Falital Aug 29 '22 at 08:45
  • Okay but guard is still not being used – Sj L Aug 30 '22 at 07:04
  • I skiped error checking in my example code, guard either points to the next part of the date not used by strptime or NULL in which case strptime failed. – Falital Aug 30 '22 at 14:27
  • Okay, so I can see how to convert string into local/utime, but how would I convert this into number of minutes or seconds in reference to a date/time? – Sj L Aug 31 '22 at 08:18
  • The localTime/utcTime variables are Unix Timestamps, a Unix Timestamp is the number of seconds between a particular date and the Unix Epoch. Unix Epoch is on January 1st, 1970 at UTC. To covert them to minutes you have to divide them by 60. – Falital Aug 31 '22 at 11:45