C plus plus program to find the current time?


Here is a simple C++ program that displays the current system time using the C++ standard library (<ctime> and <iostream>):

#include <iostream> #include <ctime> int main() { // Get current time as time_t object time_t now = time(0); // Convert to local time structure tm *localTime = localtime(&now); // Display the current time std::cout << "Current Time: "; std::cout << localTime->tm_hour << ":" << localTime->tm_min << ":" << localTime->tm_sec << std::endl; return 0; }

Example Output:

sql
Current Time: 14:35:27

Explanation:

  • time(0) gets the current time as seconds since the Epoch (January 1, 1970).

  • localtime() converts that to a tm structure containing local time info.

  • tm_hour, tm_min, and tm_sec give hours, minutes, and seconds.

Let me know if you want it in 12-hour format, with AM/PM, or using C++20 <chrono> instead.


1. Current Time with Date and AM/PM Format


#include <iostream> #include <ctime> #include <iomanip> int main() { time_t now = time(0); tm *localTime = localtime(&now); int hour = localTime->tm_hour; std::string meridian = (hour >= 12) ? "PM" : "AM"; hour = (hour % 12 == 0) ? 12 : hour % 12; // Convert to 12-hour format std::cout << "Current Date: " << (localTime->tm_mday) << "/" << (localTime->tm_mon + 1) << "/" << (localTime->tm_year + 1900) << std::endl; std::cout << "Current Time: " << std::setw(2) << std::setfill('0') << hour << ":" << std::setw(2) << std::setfill('0') << localTime->tm_min << ":" << std::setw(2) << std::setfill('0') << localTime->tm_sec << " " << meridian << std::endl; return 0; }

2. Using C++20 <chrono> Library (Modern Approach)

⚠️ Requires C++20 standard compiler support.

#include <iostream> #include <chrono> #include <format> // C++20 #include <ctime> int main() { auto now = std::chrono::system_clock::now(); std::time_t t = std::chrono::system_clock::to_time_t(now); std::cout << "Current Time: " << std::format("{:%d-%m-%Y %I:%M:%S %p}", *std::localtime(&t)) << std::endl; return 0; }

3. Realtime Clock Refreshing Every Second (Like a Clock)


#include <iostream> #include <ctime> #include <thread> #include <chrono> int main() { while (true) { std::system("clear"); // use "cls" on Windows time_t now = time(0); tm *localTime = localtime(&now); std::cout << "Current Time: " << std::setw(2) << std::setfill('0') << localTime->tm_hour << ":" << std::setw(2) << std::setfill('0') << localTime->tm_min << ":" << std::setw(2) << std::setfill('0') << localTime->tm_sec << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; }

🔧 To Compile and Run:

  • Linux/macOS (g++):

    g++ -std=c++20 filename.cpp -o timeapp ./timeapp
  • Windows (g++ or Dev C++):

    • Replace system("clear") with system("cls") for clearing the screen.

Previous Post Next Post