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

后端 未结 24 1954
刺人心
刺人心 2020-11-22 06:55

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

24条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 07:35

    the C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C, along with a couple of date/time input and output functions that take into account localization.

    // Current date/time based on current system
    time_t now = time(0);
    
    // Convert now to tm struct for local timezone
    tm* localtm = localtime(&now);
    cout << "The local date and time is: " << asctime(localtm) << endl;
    
    // Convert now to tm struct for UTC
    tm* gmtm = gmtime(&now);
    if (gmtm != NULL) {
    cout << "The UTC date and time is: " << asctime(gmtm) << endl;
    }
    else {
    cerr << "Failed to get the UTC date and time" << endl;
    return EXIT_FAILURE;
    }
    

提交回复
热议问题