If you're using C++ with a recent compiler (VisualStudio 12+), the
<chrono> library is a new standard which is portable across
platforms. That can get you an accurate timestamp. Then to convert
to a string, the platforms vary slightly if you want to use local
time. This should work to get you a printable timestamp on Linux or
Windows, with microsecond precision:
#include <chrono>
#include <iostream>
#include <time.h>
using namespace std;
using namespace std::chrono;
//#define USE_UTC
int main()
{
system_clock::time_point tp = system_clock::now();
microseconds usTm =
duration_cast<microseconds>(tp.time_since_epoch());
time_t t =
duration_cast<seconds>(usTm).count();
unsigned us = usTm.count() % 1000000;
char buf[1024];
struct tm tm;
#if defined(USE_UTC)
::gmtime_r(&t, &tm);
#else
#if defined(WIN32)
::localtime_s(&tm, &t);
#else
::localtime_r(&t, &tm);
#endif
#endif
// Equiv format: "%Y-%m-%d %H:%M:%S"
size_t n = ::strftime(buf, sizeof(buf), "%F %T",
&tm);
n += ::snprintf(buf+n, sizeof(buf)-n-1, ".%06u", us);
cout << buf << endl;
}
Uncomment 'USE_UTC' to print the timestamp in UTC time.
If you want a millisecond time stamp, you can just extract the
milliseconds from the time point in the same manner:
milliseconds msTm =
duration_cast<milliseconds>(tp.time_since_epoch());
time_t t = duration_cast<seconds>(msTm).count();
unsigned ms = msTm.count() % 1000;
and then format with 3 digits:
n += ::snprintf(buf+n, sizeof(buf)-n-1, ".%03u",
ms);
Frank
On 06/27/2014 05:05 AM, Ian Craggs
wrote:
Rahul,
in the C client, I use _ftime on Windows http://msdn.microsoft.com/en-us/library/z54t9z5f.aspx
(see Log.c) or GetTickCount for time intervals (see
MQTTClient.c). Both of those have values in milliseconds.
Ian
On 06/27/2014 04:27 AM, Rahul Gupta
wrote:
Hello Ian - Thanks for your response, I am trying to
include time stamp of publication in the payload, however
I am unable to get the time in milliseconds, so was
exploring if I could the millisecond value using a CPP
program.
Thanks,
Rahul
_______________________________________________
paho-dev mailing list
paho-dev@xxxxxxxxxxx
https://dev.eclipse.org/mailman/listinfo/paho-dev
--
Ian Craggs
icraggs@xxxxxxxxxx IBM United Kingdom
Committer on Paho, Mosquitto
_______________________________________________
paho-dev mailing list
paho-dev@xxxxxxxxxxx
https://dev.eclipse.org/mailman/listinfo/paho-dev
|