C++ || Convert Time From Seconds Into Hours, Min, Sec Format
Here is another simple programming assignment. This page will demonstrate how to convert time from -seconds- into HH::MM::SS (hours, minutes seconds) format. So for example, if you had an input time of 9630 seconds, the program would display the converted time of 2 hours, 40 minutes, and 30 seconds.
Using simple math, this program utilizes the modulus operator, and the division operator during the conversion process.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Modulus - What is it?
How Many Seconds Are In One Hour?
How Many Seconds Are In One Minute?
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 30, 2012 // Taken From: http://programmingnotes.org/ // File: Convert-Time.cpp // Description: Demonstrates how to convert time from -seconds- into // HH::MM::SS (hours, minutes, seconds) format // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0; }// 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
(Note: the code was compiled five separate times to display different output)
====== RUN 1 ======
Enter a time in seconds: 9630
The time in HH:MM:SS format is: 2 hours, 40 minutes, and 30 seconds!
====== RUN 2 ======
Enter a time in seconds: 7200
The time in HH:MM:SS format is: 2 hours, 0 minutes, and 0 seconds!
====== RUN 3 ======
Enter a time in seconds: 45
The time in HH:MM:SS format is: 0 hours, 0 minutes, and 45 seconds!
====== RUN 4 ======
Enter a time in seconds: 134
The time in HH:MM:SS format is: 0 hours, 2 minutes, and 14 seconds!
====== RUN 5 ======
Enter a time in seconds: 31536000
The time in HH:MM:SS format is: 8760 hours, 0 minutes, and 0 seconds!
Not run this your program
Thank you for the code. 🙂
Write a program that reads in a time in seconds, and computes how many hours and minutes it contains. Thus, 3700 should yield: 1 hour, 1 minute, and 40 seconds. (Hint: use the mod function)
this program is so good i completely understand its code .thank you so much
what does mean that % sight? What he do?