C++ || Snippet – How To Display The Current System Time & Date In C++
This page consists of a simple program which demonstrates the process of displaying the current system time and date in C++.
This program utilizes the use of a “struct” data structure to obtain the necessary information to display the current system date and time. Knowledge of how this process works would be beneficial, but is not necessary. Click here for more information on how structs work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 23, 2012 // Updated: Feb 6, 2021 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: Demonstrates how to display the current system time // ============================================================================ #include <iostream> #include <ctime> // used for time #include <iomanip> // used for setw std::tm getLocalTime(std::time_t timer); int main() { // variable declaration for the current time auto now = getLocalTime(std::time(0)); // display the current date in MM/DD/YYYY format std::cout << "Today's Date is: " << (now.tm_mon + 1) << "/" << (now.tm_mday) << "/" << (now.tm_year + 1900) << std::endl; // display the current system time in HH:MM:SS, AM/PM format std::cout << "\nThe current system time is: "; // display the hours if (now.tm_hour == 0) { std::cout << 12; } else { std::cout << now.tm_hour % 12; } std::cout << ":"; // display the current mins/secs std::cout.fill('0'); std::cout << std::setw(2) << (now.tm_min) << ":" << std::setw(2) << (now.tm_sec); // display AM/PM if (now.tm_hour >= 12) { std::cout << " PM"; } else { std::cout << " AM"; } std::cout << std::endl; std::cin.get(); return 0; }// end of main std::tm getLocalTime(std::time_t timer) { std::tm bt{}; #if defined(_MSC_VER) localtime_s(&bt, &timer); #else localtime_r(&timer, &bt); #endif return bt; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Today's Date is: 2/23/2012
The current system time is: 1:05:43 PM
thanks for sharing.
useful information