How do I get the current date and time in C++?

Asked 2 years ago, Updated 2 years ago, 117 views

I want to know the current time and date regardless of the platform. Help me

c++ date time cross-platform

2022-09-22 14:26

1 Answers

Code that works regardless of platform is as follows:

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

// Function that returns the current time to string type
const std::string currentDateTime() {
    time_t now = time(0); //Save the current time as time_t type
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); // YYYY-MM-DD.String in the form of HH:mm:ss

    return buf;
}

int main() {
    std::cout << "Now is the time:" << currentDateTime() << std::endl;
}

Result: This time is:2016-01-15.18:44:25

For the datetime format, see here


2022-09-22 14:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.