HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How can I get current time and date in C++?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howanddatetimecurrentcanget

Problem

Is there a cross-platform way to get the current date and time in C++?

Solution

Since C++11, you can use std::chrono::system_clock::now().

Example (copied from en.cppreference.com):

#include 
#include 
#include 

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s"
              << std::endl;
}


This should print something like this:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s

Code Snippets

#include <iostream>
#include <chrono>
#include <ctime>

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s"
              << std::endl;
}

Context

Stack Overflow Q#997946, score: 944

Revisions (0)

No revisions yet.