Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

System.currentTimeMillis() in C++ 2

Status
Not open for further replies.

titanandrews

Programmer
Feb 27, 2003
130
US
Hi,
Is there an equivalent C++ function to the System.currentTimeMillis() method in Java? I need the time to be recorded in the exact same format and precision.

thank you very much,

Barry
 
The following win32 functions may be helpful:

GetTickCount(); // number of milliseconds your computer has been on. returns DWORD

and

timeGetTime(); // returns a DWORD, used with timeBeginPeriod(1) and timeEndPeriod(1) to set the min and max period

Look these two functinos up at MSDN for details. Since they are both win32 functions I think they require #include<windows.h>.

-Bones
 
Java currenTimeMillis() returns Java long type (64 bit by definition). Current (most of) MS C++ implementations have 32 bit long type. It's too small to present millisecs from 1970/1/1. We must use MS extention type __int64 (non-standard!). Now:
Code:
#include <windows.h>
#include <cstring>
__int64 currentTimeMillis()
{
static const __int64 magic = 116444736000000000; // 1970/1/1
  SYSTEMTIME st;
  GetSystemTime(&st);
  FILETIME   ft;
  SystemTimeToFileTime(&st,&ft); // in 100-nanosecs...
  __int64 t;
  memcpy(&t,&ft,sizeof t);
  return (t - magic)/10000; // scale to millis.
}
In seconds basis precision surrogate is time() library function:
Code:
#include <ctime>
inline long currentTimeSecs()
{
  return time(0);
}
time(0) returns time_t type (one of long integral type).
Warning: you can't multiply these seconds value to 1000 - 32-bit overflow...
 
Thanks ArkM! That is a brilliant solution, and exactly what I was looking for!


Barry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top