c++ localtime to mysql datetime - c++

I have a c++ time double that records seconds since 1 Jan 1970.
I want to convert this double and store it in a MySQL database, so here is my code to convert it firstly to a datetime format: *NOTE: ss.time is the double..
/* do the time conversion */
time_t rawtime;
struct tm * timeinfo;
rawtime = (time_t)ss.time;
timeinfo = localtime(&rawtime);
This code converts it to the following format: Thu Jul 24 05:45:07 1947
I then attempt to write it to the MySQL database as follows:
string theQuery = "UPDATE readings SET chng = 1, time = CAST('";
theQuery += boost::lexical_cast<string>(asctime(timeinfo));
theQuery += "' AS DATETIME) WHERE id = 1";
It does not work, but updates the time DATETIME variable in the table with NULL.
Can someone tell me how to do a correct conversion and update the SQL table?

Your c++ double is just a standard Unix timestamp, which MySQL can convert using its FROM_UNIXTIME function:
UDPATE ... SET ... time=FROM_UNIXTIME(rawtime)

Related

Convert Long of Unix Epoch Timestamp to Real Date/Time

I have attempted to find an answer to this question but the sources I have found do not properly convert the time. Originally I have the timestamp in a string as I am getting the timestamp from a .json web scraping program but want to convert it to a readable date/time. My latest attempt to do the conversion was to convert the string into a long and the long to time_t and then use strftime() but that does not produce the correct answer.
Here is the code where I converted the string to a long and then to time_t and then used strftime()
std::string timeStampToRead(const time_t rawtime)
{
struct tm *dt;
char buffer [30];
dt = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%m%d %H%M", dt);
return std::string(buffer);
}
int main()
{
std::string epochT = "1604563859000";
long e = atol(epochT.c_str());
const time_t rawtime = (const time_t)e;
std::string time = timeStamptToRead(rawtime);
return 0;
}
The result of this code is 0808 1703
I also attempted to do something very similar to above but changed timeStampToRead to the following
std::string timeStampToRead(const time_t rawtime)
{
struct tm *dt;
char buffer [30];
dt = localtime(&rawtime);
return asctime(dt);
}
This returns Mon Aug 8 17:03:20 which is also incorrect
The correct answer should be Thursday, November 5, 2020 8:10:59 UTC or Thursday, November 5, 2020 1:10:59 locally (not necessarily in that exact format just the correct month, day, and time is important)
I have tested the outcome of converting the string to a long and that is working correctly so I am thinking the error is either in converting the long to time_t or the process of using the time_t to get a readable format of the time. Of the two options, I think it is more likely the conversion from long to time_t is the issue but can't find another way to do the conversion.
I was hoping there was an easy way to directly take the string and convert it but I cannot find any information on that anywhere so that is why I resulted to converting the string to long and then to time_t. Basically, I can't figure out how to convert a string or long unix epoch timestamp to time_t to convert it to a readable format, or at least that is where I am assuming the error is. If anyone could point me in the right direction to get this conversion code working I would greatly appreciate it.
After some further digging, I have found my error and determined the best route
std::string epochT = "1604563859000";
long e atol(epochT.c_str());
const time_t rawtime = e/1000;
struct tm * dt;
dt = localtime(&rawtime);
std::string readable = asctime(dt);
This code will be inside a for loop that iterates through vectors of strings so epochT will be dependent on the elements in the vector and the current element, but this works and outputs the correct answer of Thu Nov 5 01:10:59 2020 local time.

ESP32 setenv() and localtime() from UTC time string

please consider following code, it compiles and run on ESP32 board:
unsetenv("TZ");
String payload = http.getString();
payload.replace("\"", "");
Serial.print("Payload: ");
Serial.println(payload);
const char* format = "%Y-%m-%dT%H:%M:%S";
strptime(payload.c_str(), format,& _time);
//debug only
Serial.print("Chamber time(UTC): ");
char chDate[11] = "";
char chTime[9] = "";
strftime(chDate, 11, "%m/%d/%Y", &_time);
strftime(chTime, 9, "%H:%M:%S", &_time);
Serial.print(chDate);
Serial.print(" ");
Serial.println(chTime);
int epoch_time = mktime(&_time);
timeval epoch = { epoch_time, 0 };
const timeval* tv = &epoch;
settimeofday(tv, NULL);
int rcode = setenv("TZ", "EST+5", 1);
tzset();
Serial.print("SetEnv reply");
Serial.println(rcode);
//VERIFICA
struct tm now;
getLocalTime(&now, 0);
Serial.println(&now, " %B %d %Y %H:%M:%S (%A)");
producing the following output:
Payload: 2020-04-08T21:59:10.736+0000
Chamber time(UTC): 04/08/2020 21:59:10
SetEnv reply0
April 08 2020 21:59:10 (Wednesday)
I expected the last date to be a local time according to "EST+5" timezone, in this example. Infact, I followed this readme, as I am using a ESP32 board, that says:
To set local timezone, use setenv and tzset POSIX functions. First,
call setenv to set TZ environment variable to the correct value
depending on device location. Format of the time string is described
in libc documentation. Next, call tzset to update C library runtime
data for the new time zone. Once these steps are done, localtime
function will return correct local time, taking time zone offset and
daylight saving time into account
What am I missing/doing wrong, apart from my rusty C++? Perfect solution would be to use : format like ":Europe/Rome" Thanks
The TZ string "EST+5" might be unknown to the OS, supported by the fact your output showed UTC time. EST and EDT have been used for US Eastern or America/New York. Assuming this is a Linux-like OS, take a look in the /usr/share/zoneinfo/ path for the zones available, or try the tzselect command to see if you can find the correct TZ string.
Try this sequence of C functions:
time_t tnow;
time(&tnow);
struct tm when;
errno_t ret = localtime_s(&when, &tnow);
// struct tm *when = localtime(&tnow); // deprecated for some compilers
The getLocalTime() function is not standard C and may not honor tzset().

UTC Timestamp comparison

I'm working on a client-server custom application (to be run on linux), and one of the frames I send include a timestamp (ie the time at which the frame is send).
In order to make my application reliable, I used gmtime to produce the time on the client. I'm in Belgium, so right now the hour of the client VM is 2 hours later than the UTC time (because of the summer hour).
In the server side, I first convert the recieved string to a time_t type. I do this to use the difftime function to see if the timestamp is not too old.
Then, I generate a timestamp (in UTC time) again with gmtime, and I convert it to a time_t.
I compare then the two time_t to see the time difference.
I have got a problem with the conversion of the time at the server side. I use the same code as in the client, but the outputted gmtime is different...
Client Side : function to generate the timestamp, and export it to a string (time_str):
std::string getTime()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime); // Get time of the system
timeinfo = gmtime(&rawtime); // Convert it to UTC time
strftime(buffer,80,"%d-%m-%Y %H:%M:%S",timeinfo);
std::string time_str(buffer); // Cast it into a string
cout<<"Time Stamp now (client) : "<<time_str<<endl;
return time_str;
}
And it produices this (at 9h33 local time) :
Time Stamp now : 06-04-2016 07:33:30
Server Side : fucntion to retrieve the timestamp, generate the newx time stamp, and compare them :
bool checkTimeStamp(std::string TimsStamp_str, double delay)
{
cout<<"TimeStamp recieved: "<<TimsStamp_str<<endl;
/* Construct tm from string */
struct tm TimeStampRecu;
strptime(TimsStamp_str.c_str(), "%d-%m-%Y %I:%M:%S", &TimeStampRecu);
time_t t_old = mktime(&TimeStampRecu);
/* Generate New TimeStamp */
time_t rawtime;
struct tm * timeinfo;
time (&rawtime); // Get time of the system
timeinfo = gmtime(&rawtime); // convert it to UTC time_t
time_t t2 = mktime(timeinfo); // Re-Cast it to timt_t struct
/* Convert it into string (for output) */
char buffer[80];
strftime(buffer,80,"%d-%m-%Y %H:%M:%S",timeinfo);
std::string time_str(buffer); // Cast it into a string
cout<<"Time Stamp now (server) : "<<time_str<<endl;
/* Comparison */
double diffSecs = difftime(t2, t_old);
cout<<diffSecs<<endl;
bool isTimeStampOK;
if (diffSecs < delay)
isTimeStampOK = true;
else
isTimeStampOK = false;
return isTimeStampOK;
}
And it produces this (at 9h33 in Belgium) :
TimeStamp recieved : 06-04-2016 07:33:30
Time Stamp now (server) : 06-04-2016 08:33:31
Why is the Server Time (8h33) neither in localtime (9h33), neither in UTC time (7h33) ?
Have I made a mistake in its generation ? I don't understand where, because these are the exact same code as in the client side...
There's a couple of errors in your code, some your fault, some not. The biggest problem here is that the C <time.h> API is so poor, confusing, incomplete and error prone that errors like this are very nearly mandatory. More on that later.
The first problem is this line:
struct tm TimeStampRecu;
It creates an uninitialized tm and then passes that into strptime. strptime may not fill in all the fields of TimeStampRecu. You should zero-initialize TimeStampRecu like this:
struct tm TimeStampRecu{};
Next problem:
strptime(TimsStamp_str.c_str(), "%d-%m-%Y %I:%M:%S", &TimeStampRecu);
The 12-hour time denoted by %I is ambiguous without an AM/PM specifier. I suspect this is just a type-o as it is the only place you use it.
Next problem:
gmtime time_t -> tm UTC to UTC
mktime tm -> time_t local to UTC
That is, mtkime interprets the input tm according to the local time of the computer it is running on. What you need instead is:
timegm tm -> time_t UTC to UTC
Unfortunately timegm isn't standard C (or C++). Fortunately it probably exists anyway on your system.
With these changes, I think your code will run as expected.
If you are using C++11, there is a safer date/time library to do this here (free/open-source):
https://github.com/HowardHinnant/date
Here is your code translated to use this higher-level library:
std::string getTime()
{
using namespace std::chrono;
auto rawtime = time_point_cast<seconds>(system_clock::now());
auto time_str = date::format("%d-%m-%Y %H:%M:%S", rawTime);
std::cout<<"Time Stamp now (client) : "<<time_str<< '\n';
return time_str;
}
bool checkTimeStamp(std::string TimsStamp_str, std::chrono::seconds delay)
{
using namespace std::chrono;
std::cout<<"TimeStamp recieved: "<<TimsStamp_str<< '\n';
/* Construct tm from string */
std::istringstream in{TimsStamp_str};
time_point<system_clock, seconds> t_old;
date::parse(in, "%d-%m-%Y %H:%M:%S", t_old);
/* Generate New TimeStamp */
auto rawtime = time_point_cast<seconds>(system_clock::now());
auto time_str = date::format("%d-%m-%Y %H:%M:%S", rawTime);
in.str(time_str);
time_point<system_clock, seconds> t2;
date::parse(in, "%d-%m-%Y %H:%M:%S", t2);
cout<<"Time Stamp now (server) : "<<time_str<<endl;
/* Comparison */
auto diffSecs = t2 - t_old;
cout<<diffSecs.count()<<endl;
bool isTimeStampOK;
if (diffSecs < delay)
isTimeStampOK = true;
else
isTimeStampOK = false;
return isTimeStampOK;
}
A timestamp is an absolute value. It doesn't depend on timezones or DST. It represents the number of seconds since a fixed moment in the past. The value returned by time() is the same, no matter what the timezone of the server is.
Your code doesn't produce timestamps but dates formatted for human consumption.
I recommend you use timestamps internally and format them to dates readable by humans only in the UI. However, if you need to pass dates as strings between various components of your application, also put the timezone in them.
I would write your code like this (using only timestamps):
// The client side
time_t getTime()
{
return time(NULL);
}
// The server side
bool checkTimeStamp(time_t clientTime, double delay)
{
time_t now = time(NULL);
return difftime(now, clientTime) < delay;
}
Update
If you have to use strings to communicate between client and server then all you have to do is to update the format string used to format the timestamps as dates (on the client) and parse the dates back to timestamps (on the server), to include the timezone you used to format the date.
This means add %Z into the format everywhere in your code. Use "%d-%m-%Y %H:%M:%S %Z". Btw, the code you posted now reads "%d-%m-%Y %I:%M:%S" in the call to strptime() and that will bring you another problem in the afternoon.
Remark
I always use "%Y-%m-%d %H:%M:%S %Z" because it is unambiguous and locale-independent. 06-04-2016 can be interpreted as April 6 or June 4, depending of the native language of the reader.

C++ mktime returning random dates

I'm trying to convert a date string to a time_t, but mktime() is returning seemingly random dates:
string datetime = "2014-12-10 10:30";
struct tm tmInfo;
strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);
tmInfo.tm_isdst = 0;
time_t eventTime = mktime(&tmInfo);
eventTime ranges wildly from the 1970s to the 2030s. The tmInfo struct holds the correct date, so the error must be happening in mktime(). Any ideas of what's going wrong?
You need to properly zero-initialize all of the other fields of the struct tm instance before calling strptime(), since it doesn't necessarily initialize every field. From the strptime() POSIX specification:
It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.
For example, this should suffice:
struct tm tmInfo = {0};
You have to initialize the struct to 0 beforehand or also input the seconds:
string datetime = "2014-12-10 10:30";
struct tm tmInfo = { 0 };
strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);
or
string datetime = "2014-12-10 10:30:00";
struct tm tmInfo;
strptime(datetime.c_str(), "%Y-%m-%d %H:%M:%S", &tmInfo);
The below code would do the work, if you want current system time in an format
time_t current_time;
struct tm *loctime;
memset(buffer,0,strlen(buffer));
current_time = time(NULL);
loctime = localtime(&current_time);
strftime(buffer,250,"--> %d/%m/%y %H:%M:%S",loctime);

Convert RFC 822 timestamp to unixtime, timezone values not working , C/C++

I've a function which converts an RFC 822 timestamp to unixtime
#include <stdio.h>
#include <time.h>
int main() {
struct tm tm;
time_t unixtime;
strptime("Sun, 20 Feb 2011 10:28:02 +0800","%a, %e %h %Y %H:%M:%S %z",&tm);
unixtime = mktime(&tm);
printf("%d\n",unixtime);
return 0;
}
Problem: The timezone part (%z) doesn't seem to be working. I tried changing input timezone to other values +0100, + 0200 ect without changing other date values, it always gives the same unixtime stamp (ie, unixtimestamp corresponding to GMT)
What can be the issue here ?
struct tm does not contain a timezone field. %z is supported simply to support the same flags as strftime. You'll need to extract and adjust the timezone offset manually.