Home > Backend Development > C++ > How Do I Get the Current Date and Time in C ?

How Do I Get the Current Date and Time in C ?

Patricia Arquette
Release: 2024-12-20 01:54:09
Original
596 people have browsed it

How Do I Get the Current Date and Time in C  ?

How to Obtain the Current Time and Date in C

In C , there's a platform-independent approach to retrieving the current date and time:

std::chrono::system_clock::now()

Introduced in C 11, this function provides a portable method to access the system clock's current time. Here's an example adapted from en.cppreference.com:

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

int main() {
    auto start = std::chrono::system_clock::now();
    // Some computation
    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;
}
Copy after login

This code will output a timestamp similar to:

Finished computation at Mon Oct  2 00:59:08 2017
Elapsed time: 1.88232s
Copy after login

The above is the detailed content of How Do I Get the Current Date and Time in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template