April 18, 2016 · tech interviews c++ cpp

Getting a unix timestamp in C++

Choosing C++ as an interview-language for a code exercise?

Things like getting the current timestamp in seconds can trip candidates up.

Here's a quick recipe when you're in a bind:

http://codepad.org/GvmWaqVZ

#include <ctime>
#include <iostream>

long int unix_timestamp()  
{
    time_t t = std::time(0);
    long int now = static_cast<long int> (t);
    return now;
}

int main()  
{
    long int now = unix_timestamp();
    std::cout << now;
}

The above should output something like:

1461013984  

Cheers.