Question

I need a function or library to get the current system time in milliseconds from 1/1/1970 (C++) ?

I need to get a unsigned double number containing the milliseconds from 1/1/1970.

The operating system is Windows.

ADDITIONAL INFO:

Need to synchronize the server application and the client. The client is the master. The client tells the server when he needs to do something. After that the server runs on its own. I am sending the time stamp from the client that contains the current system time down to the millisecond level. The Server once received this message must do the same thing. He must get the time stamp and the difference will be the number of milliseconds to adjust its timeline. This is a matter of how to synchronize to process to do some related work at the same time.

DO NOT WANT TO USE BOOST IF IT IS POSSIBLE !

Was it helpful?

Solution

You can use GetSystemTimeAsFileTime to get the current time as a FILETIME. Create a SYSTEMTIME representing your desired epoch (1/1/1970) and call SystemTimeToFileTime to convert it to a FILETIME. Subtract the two FILETIMEs and scale to your desired accuracy (from 100ns units to 1ms units).

This will give you the current UTC time. If you need the local time, you'll need to convert to local time using e.g. SystemTimeToTzSpecificLocalTime.

OTHER TIPS

It's not mandated by the standard, but I understand that all major implementations of std::chrono::system_clock use 1970-1-1 as the epoch and generally have at least millisecond resolution. So in practice you can simply do:

#include <chrono>
#include <iostream>

int main() {
    auto now = std::chrono::system_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() << '\n';
}

you can use boost for geting your time duration. boost/date_time/gregorian/gregorian.hpp provides a function date_duration() which can calculate dates from the year 1400 up to today.

Check out this std::clock() it should have the functionality you need to get the millisecond count.

Another thing to look for is "epoch" time.

In Windows use GetSystemTime. Here's the link to MSDN

You'll need to sum up the components, but that's trivial :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top