Converting seconds to hours and minutes and seconds - c++

#include <cstdio>
#include <iostream>
using namespace std;
int main ()
{
int seconds, hours, minutes;
cin >> seconds;
hours = seconds/3600;
cout << seconds << " seconds is equivalent to " << int(hours) << " hours " << seconds%(hours*60)
<< " minutes " << (seconds%(hours*3600))-((seconds%(hours*60))*60) << " seconds.";
}
For some reason, this program works with only numbers above 3600. Does anyone know how to fix this problem? Whenever I do a number below 3600, the screen shows up with a message from Windows saying that the program has stopped working.

Try this out instead, tested and works:
int seconds, hours, minutes;
cin >> seconds;
minutes = seconds / 60;
hours = minutes / 60;
cout << seconds << " seconds is equivalent to " << int(hours) << " hours " << int(minutes%60)
<< " minutes " << int(seconds%60) << " seconds.";
Because minutes is seconds/60, dividing it by 60 again is equivalent to diving seconds by 3600, which is why it works.

seconds/3600 is integer division, so for seconds < 3600, hours is 0, then things like seconds%(hours*3600) becomes seconds % 0, causing a division-by-zero.
Let's first get the logic right. Suppose you want to write 5000 seconds as x hours y minutes z seconds, such that all three are integers and neither y nor z is greater than 59. What do you do?
Well, you can first write it as q minutes z seconds, such that both are integers and z is not greater than 59. That's easy:
q = 5000 / 60 = 83 // integer division
z = 5000 % 60 = 20
So 5000 seconds is 83 minutes 20 seconds. Now how do you write 83 minutes into x hours y minutes, such that both are integers and y is no greater than 59? You do the same thing:
x = 83 / 60 = 1
y = 83 % 60 = 23
OK, let's generalize this:
int total, seconds, hours, minutes;
cin >> total;
minutes = total / 60;
seconds = total % 60;
hours = minutes / 60;
minutes = minutes % 60;
cout << total << " seconds is equivalent to " << hours << " hours " << minutes
<< " minutes " << seconds << " seconds.\n" ;

You've got a divide-by-zero problem here:
seconds % (hours*60);
hours is 0 by virtue of integer division.
hours = seconds/3600;
From what you're trying to do, you should consider conditional logic to print the minutes if the total number of seconds is greater than 3600. You'll also want to investigate similar logic in the next part of your print stream.
My C++ is rusty, so forgive if this isn't exactly valid syntax:
cout << (seconds > 3600 ? seconds % (hours*60) : seconds) << endl;

Try this:
int totalSecond;
cin >> totalSecond;
int hour = totalSecond / 3600;
int minute = (totalSecond % 3600) / 60;
int second = totalSecond % 60;
cout << hour << ":" << minute << ":" << second << endl;
Assuming that totalSeconds is the number of seconds since midnight and is less than 86400

With c++20 this gets pretty easy using std::chrono::hh_mm_ss:
#include <iostream>
#include <chrono>
int main ()
{
int seconds;
std::cin >> seconds;
std::chrono::hh_mm_ss time{std::chrono::seconds(seconds)};
std::cout << seconds << " seconds is equivalent to " << time.hours().count() << " hours " << time.minutes().count()
<< " minutes " << time.seconds().count() << " seconds.";
}

by using function;
#include<iostream>
using namespace std;
int hour(int h)
{
int second;
//second=(h/3600);
if (h>3600)
second=h/3600;
else
second=(h/3600);
return (second);
}
int minute(int m)
{
int second2;
second2=( );
return(second2);
}
int second(int s)
{
int second3;
second3=((s-3600)%60);
return (second3);
}
void main()
{
int convert;
cout<<"please enter seconed to convert it to hour\b";
cin>>convert;
cout<<"hr : min : sec \n";
cout<<hour(convert)<<":"<<minute(convert)<<":"<<second(convert)<<endl;
system("pause");
}

Until now none of the presented solution have in count the day duration. I had to write a clock to use in arduino, the millis() function return milliseconds since turn on, to get seconds just divide by 1000.
void showTime(unsigned long seconds){
printf( "seconds : %lu ", seconds);
int hh = (seconds/3600) %24;
int mm = (seconds/60) %60;
int ss = seconds%60;
printf( " Time : %2d:%02d:%02d\n", hh, mm,ss);
}
showTime( 0*24*3600 + 4*3600+35*60+25); // 0d+4hs+35m+25s;
showTime( 2*24*3600 + 1*3600+45*60+59); // 2d+1hs+45m+59s;
showTime(40*24*3600 + 10*3600+ 5*60+10); // 40d+10hs+5m+10s;
wath print:
seconds : 189325 Time : 4:35:25
seconds : 6359 Time : 1:45:59
seconds : 3492360 Time : 10:06:00

Using std::chrono::duration_cast, one can simply write (refer std::chrono::duration for more options):
#include <chrono>
#include <iostream>
using namespace std::chrono;
int main() {
int s; std::cin >> s;
seconds sec(s);
std::cout << duration_cast<hours>(sec).count() << ':'
<< duration_cast<minutes>(sec).count() % 60 << ':'
<< sec.count() % 60;
}

One string convertion from seconds to hh:mm:ss format:
sprintf(tempBuffer, "%02u:%02u:%02u", _time / 3600, (_time % 3600) / 60, _time % 60);

Try this
int h,m,s;
cout << "Time in Seconds = ";
cin >> s;
cout << "H:M:S - " << s / 3600 << ":" << (s % 3600) / 60 << ":" << s % 60;
Input:
Time in Seconds = 25300
Output:
H:M:S - 7:1:40

Have a look at this code:
#include <iostream>
using namespace std;
int main()
{
int seconds;
cout << "Enter an integer for seconds: ";
cin >> seconds;
int minutes = seconds / 60;
int remainingSeconds = seconds % 60;
cout << seconds << " seconds is " << minutes <<
" minutes and " << remainingSeconds << " seconds " << endl;
return 0;
}

Related

Calculating Time Difference in military time for C++

I have to write a program that gives the difference between two times that are given in military time format. For example,
Please enter the first time: 1730
Please enter the second time: 0900
Output = 15 hours 30 minutes
Here is the program I came up with (*Not allowed to use if statements, loops or functions)
I just need to know whether this is correct or incorrect?
int main()
{
int first;
int second;
cout << "Please enter the first time:";
cin >> first;
cout << endl;
cout << "Please enter the second time:";
cin >> second;
cout << endl;
int am = first - 1200;
second = second + 1200;
int amhour = am/100;
int ammins = am%100;
int hours = second - amhour*100;
int real_hr = hours - 40;
int final_time = real_hr - ammins;
int final_hours = final_time/100;
int final_mins = final_time%100;
cout << final_hours << " hours and " << final_mins << " minutes." << endl;
return 0;
}
I would first convert each time into "minutes since midnight", then subtract the first from the second, then use that to form your output.
However, you may need to take into account that the subtraction may give you a negative number if, for example, the first time is 2330 and the second is 0030 (crossing the day boundary).
You can fix that by simply adding 1440 minutes (one day) to the difference and then using the modulo operator to reduce that if it's more than a day.
So I would start with something like:
#include <iostream>
int main() {
// Get times from user.
int first, second;
std::cout << "Please enter the first time: "; std::cin >> first;
std::cout << "Please enter the second time: "; std::cin >> second;
// Convert both to minutes since midnight.
first = (first / 100) * 60 + first % 100;
second = (second / 100) * 60 + second % 100;
// Work out time difference in minutes, taking into
// account possibility that second time may be earlier.
// In that case, it's treated as the following day.
const int MINS_PER_DAY = 1440;
int minutes = (second + MINS_PER_DAY - first) % MINS_PER_DAY;
// Turn minutes into hours and residual minutes, then output.
int hours = minutes / 60;
minutes = minutes % 60;
std::cout << hours << " hours and " << minutes << " minutes.\n";
}

Converting seconds into days, hours, minutes, seconds format (C++)

I was doing the following programming exercise:
Write a program that asks the user to enter the number of seconds as an integer
value (use type long, or, if available, long long) and that then displays the equivalent
time in days, hours, minutes, and seconds. Use symbolic constants to represent
the number of hours in the day, the number of minutes in an hour, and the number
of seconds in a minute. The output should look like this:
Enter the number of seconds: 31600000
31600000 seconds = 365 days, 17 hours, 46 minutes, 40 seconds
So I wrote this (in Microsoft Visual Studio 2015):
#include "stdafx.h"
#include iostream
int main()
{
using namespace std;
const int sec_per_min = 60;
const int min_per_hr = 60;
const int hr_per_day = 24;
cout << "Enter numbers of second: ";
long long seconds;
cin >> seconds;
int day, hr, min, sec;
day = seconds / (sec_per_min * min_per_hr * hr_per_day);
hr = (seconds - day * hr_per_day * min_per_hr * sec_per_min) / (sec_per_min * min_per_hr);
sec = seconds % sec_per_min;
min = (seconds - sec) / sec_per_min % min_per_hr;
cout << seconds << " seconds = ";
cout << day << " days, ";
cout << hr << " hours, ";
cout << min << " minutes, ";
cout << sec << " seconds.";
return 0;
}
It produced the correct outcome.
But I was wondering if there's better statements for day, hr, min, sec?
I would've done the following. I think it's much clearer:
auto n=seconds;
sec = n % sec_per_min;
n /= sec_per_min;
min = n % min_per_hr;
n /= min_per_hr;
hr = n % hr_per_day;
n /= hr_per_day;
day = n;

24HR to 12HR convert program, new values not recognized in output?

I am trying to learn C++ and have an issue with a small conversion program about time formats.
#include <iostream>
using namespace std;
void conversion(int hours, int minutes) {
if (hours > 12) {
hours -= 12;
minutes = minutes;
}
else
hours = hours;
minutes = minutes;
cout << hours << ":" << minutes << endl;
}
void output(int hours, int minutes) {
cout << hours << ":" << minutes;
}
int main() {
int hours, minutes;
cout << "Enter the hours: ";
cin >> hours;
cout << "Enter minutes: ";
cin >> minutes;
conversion(hours, minutes);
output(hours, minutes);
}
In the main function, the output call is not receiving the updated values for hours and minutes.
This has nothing to do with time formats. A much smaller program that shows the same problem is:
#include <iostream>
using namespace std;
void f(int i) {
i = 20;
}
int main() {
int i = 10;
f(i);
cout << "i is still " << i << endl;
}
The problem is that int i in the parameter list means "pass by value". The function gets a copy of the value. Any changes you make to that copy are thrown away when the function exits. Either pass by reference (void f(int& i)) or by pointer (void f(int *pi)). Look up reference and pointers in your text book.
There are also a number of issues in your function:
void conversion(int hours, int minutes) {
if (hours > 12) {
hours -= 12;
minutes = minutes; // This line does nothing.
}
else
hours = hours; // This line does nothing.
minutes = minutes; // This line will get executed even if hours was originally
// >12. (Only the hours=hours line is covered by the else).
cout << hours << ":" << minutes << endl;
}
You probably wanted:
void conversion(int& hours, int& minutes) {
if (hours > 12) {
hours -= 12;
}
cout << hours << ":" << minutes << endl;
}

Get seconds until end of month in C++

I have a requirement to get time interval until end of month in C++. Are there any C++ APIs which can easily do that for me?
I need to start a timer which will expire at the first day of next month at 00:00:00 hours. For that, I need to compute the time interval i.e. number of seconds from now till end of this month.
Its rather straight foward. Get the difference in number of days between now and the last day of the month. Then get the number of seconds in a day.
Now you have the number of seconds till the end of the month, now subtract that with the number of seconds right now so far today and you will get the number of seconds until the end of the month.
#include <time.h>
#include <iostream>
using namespace std;
int main(){
int day1,month1,year1;
int day2,month2,year2;
int i,temp,DaysDiff=0;
int month[]={31,28,31,30,31,30,31,31,30,31,30,31};
int totalDiffDaysSecs=0;
int nowSeconds=0;
int expire=1000;
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout<<"\n";
day1=now->tm_mday;
month1=(now->tm_mon + 1);
year1=(now->tm_year + 1900);
day2=31;
month2=7;
year2=2015;
temp=day1;
for(i=month1;i<month2+(year2-year1)*12;i++){
if(i>12){
i=1;
year1++;
}
if(i==2){
if(year1%4==0 && (year1%100!=0 || year1%400==0))
month[i-1]=29;
else
month[i-1]=28;
}
DaysDiff=DaysDiff+(month[i-1]-temp);
temp=0;
}
cout <<"Current Time = "<< now->tm_hour << ":" << now->tm_min << "."<<now->tm_sec<<"\n";
cout <<"Today's date "<< (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << " \n";
cout <<"Target date "<< year2 << '-' << month2 << '-' << day2 << " \n";
DaysDiff=DaysDiff+day2-temp;
cout<<"Target Month = "<<i<<"\n";
cout<<"Days in Target month = "<<month[i-1]<<"\n";
cout<<"Days diff Today - Target Month = "<<DaysDiff<<" \n";
totalDiffDaysSecs=DaysDiff*24*60*60;
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
cout<<"Total seconds in a day = "<<24*60*60<<" \n";
cout<<"current total seconds so far today = "<< nowSeconds <<"\n";
cout<<"Total number of seconds in "<< DaysDiff <<" days = "<< totalDiffDaysSecs <<"\n";
cout<<"\n\n";
while(expire>0){
t = time(0); // get time now
now = localtime( & t );
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
expire=totalDiffDaysSecs - nowSeconds;
cout <<"Seconds until end of month = "<< expire <<" \r";
}
cout<<"\n\n";
cout<<"Countdown expired.\n\n";
return 0;
}

Convert seconds to Days, Minutes and Seconds

Hey everyone. I've continuing to learn C++ and I've been set the 'challenge' of converting seconds to format as the Days,Minutes and Seconds.
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
using namespace std;
const int hours_in_day = 24;
const int mins_in_hour = 60;
const int secs_to_min = 60;
long input_seconds;
cin >> input_seconds;
long seconds = input_seconds % secs_to_min;
long minutes = input_seconds / secs_to_min % mins_in_hour;
long days = input_seconds / secs_to_min / mins_in_hour / hours_in_day;
cout << input_seconds << " seconds = "
<< days << " days, "
<< minutes << " minutes, "
<< seconds << " seconds ";
return 0;
It works and comes up with the correct answer but after completing it I looked at how other people had tackled it and theirs was different. I'm wondering If I'm missing something.
Thanks, Dan.
this seems to me to be the easiest way to convert seconds into DD/hh/mm/ss:
#include <time.h>
#include <iostream>
using namespace std;
time_t seconds(1641); // you have to convert your input_seconds into time_t
tm *p = gmtime(&seconds); // convert to broken down time
cout << "days = " << p->tm_yday << endl;
cout << "hours = " << p->tm_hour << endl;
cout << "minutes = " << p->tm_min << endl;
cout << "seconds = " << p->tm_sec << endl;
I hope it helps!
Regards,
Stoycho
One of the things about programming is that there is never just one way to do something. In fact if I were to set my mind to it, I might be able to come up with a dozen completely different ways to accomplish this. You're not missing anything if your code meets requirements.
For your amusement, here's a way to format up hours:minutes:seconds under Windows (elapsed is a double & represents number of seconds elapsed since... something)
sprintf_s<bufSize>(buf, "%01.0f:%02.0f:%02.2f", floor(elapsed/3600.0), floor(fmod(elapsed,3600.0)/60.0), fmod(elapsed,60.0));
I think is the challenge from Stephen Prata's book. I did it as follows:
#include <iostream>
using namespace std;
int main()
{
long input_seconds = 31600000;
const int cseconds_in_day = 86400;
const int cseconds_in_hour = 3600;
const int cseconds_in_minute = 60;
const int cseconds = 1;
long long days = input_seconds / cseconds_in_day;
long hours = (input_seconds % cseconds_in_day) / cseconds_in_hour;
long minutes = ((input_seconds % cseconds_in_day) % cseconds_in_hour) / cseconds_in_minute;
long seconds = (((input_seconds % cseconds_in_day) % cseconds_in_hour) % cseconds_in_minute) / cseconds;
cout << input_seconds << " seconds is " << days << " days, " << hours << " hours, " << minutes << " minutes, and " << seconds << " seconds.";
cin.get();
return 0;
}
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
Really?
$ bc
365*24*60*60 + 46*60 + 40
31538800
365*24*60*60 + 1066*60 + 40
31600000
Did you mean "convert the input into days, hours, minutes and seconds, and then discard the hours" or "convert the input into days, total minutes within a day (i.e. can be more than 60), and seconds"?
In the second case I think you should replace the instruction for minutes with
long minutes = input_seconds / secs_to_min % (mins_in_hour * hours_in_day);