Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time and date in C++?

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

like image 654
Max Frai Avatar asked Jun 15 '09 19:06

Max Frai


People also ask

What is current time in C?

The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy.

How do I print the time in printf?

printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, ptm->tm_min, ptm->tm_sec); We use the tm_hour , tm_min , and tm_sec members to express a human-readable time format.

How will you print the date in below format using C?

One way to check this: Just initialize the variable and then take input. int date = 0, month = 0, year = 0; scanf("%d/%d/%d", &date, &month, &year); Now, if you give 10-12-2016 as input, you will get 10-0-0 as output.


1 Answers

In C++ 11 you can use std::chrono::system_clock::now()

Example (copied from en.cppreference.com):

#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\n"; } 

This should print something like this:

finished computation at Mon Oct  2 00:59:08 2017 elapsed time: 1.88232s 
like image 159
Frederick The Fool Avatar answered Oct 01 '22 19:10

Frederick The Fool