Arda Demir Arda Demir - 2 months ago 10
C++ Question

How to Visual c++ like javascript date?

Visual c++ like Javascrit (new Date()).getTime() function?
Function return (1475262776012) milliseconds.

Answer

According to w3schools, getTime returns the number of milliseconds since the Unix epoch. Basic C and C++ timekeeping, time_t operates in seconds.

The Modern C++ approach is to take advantage of the chrono library

#include <iostream>
#include <chrono>
int main()
{
    using namespace std::chrono; // just to shorten the namespacing

    //get the current time in highest possible precision
    auto cur_time = high_resolution_clock::now();

    //get the distance between now and the start of unix time 
    auto unixtime = cur_time.time_since_epoch();

    // convert to milliseconds
    auto unixtime_in_ms = duration_cast<milliseconds>(unixtime);

    // convert to a number and output
    std::cout << unixtime_in_ms.count();
}

If you want to, most of that can be shortened into this ugly one-liner:

auto unixtime_in_ms = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch()).count();