Home >Backend Development >C++ >How Can I Get the Current Date and Time in C Cross-Platform?

How Can I Get the Current Date and Time in C Cross-Platform?

Barbara Streisand
Barbara StreisandOriginal
2025-01-03 05:59:46882browse

How Can I Get the Current Date and Time in C   Cross-Platform?

Acquiring the Current Time and Date in C : A Cross-Platform Approach

Obtaining the current date and time is a common task in various programming scenarios. C offers a cross-platform solution through the C 11 standard, enabling developers to retrieve this information consistently across different operating systems.

Solution Using std::chrono::system_clock::now()

The std::chrono library, introduced in C 11, provides a standardized interface for working with time and dates. The function std::chrono::system_clock::now() returns a system_clock object representing the current system time.

Example Implementation

Below is an example code snippet demonstrating how to use std::chrono::system_clock::now():

#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;
    return 0;
}

When you run this code, it will print the current time, followed by the duration of any computations performed between the start and end time measurements.

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

Statement:
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