Here's a bit of code from another question which adds 29.0 minutes to 60.0 seconds and displays the result in hours:
cout <<
static_cast<quantity<hour_base_unit::unit_type>>
(quantity<time>{29.0 * minute_base_unit::unit_type()} + 60.0 * seconds)
<< endl;
What's the recommended way to define minutes so that the above expression can be written as:
cout <<
static_cast<quantity<hour_base_unit::unit_type>>
(29.0 * minutes + 60.0 * seconds)
<< endl;
If you can, I would recommend using C++14's <chrono> facilities for this. They are very nice. (I know this is not technically an answer to his question, but it might save him a lot of work).
#include <iostream>
#include <chrono>
int main () {
using namespace std::chrono;
std::cout << duration_cast<hours>(29min + 60s).count() << std::endl;
}
Related
This question already has answers here:
Converting seconds to hours and minutes and seconds
(11 answers)
Closed 9 months ago.
I am trying to solve a problem where I have a total seconds variable, from which I am trying to determine the hours, minutes and seconds.
I do not want to use any external libraries for this task.
What I have noticed is that my seconds variable seems to result in 1 less than the actual value when it is in int form,
but when it is in double form the answer is correct. Why is this?
I would welcome a different approach, perhaps using the remainder operator.
// Example program
#include <iostream>
#include <string>
int main()
{
int total_seconds;
total_seconds = 3870;
int hours, minutes, seconds;
double total_h, total_m, total_s;
int total_hours_int, total_minutes_int;
total_h = (double)total_seconds / 3600;
total_hours_int = total_seconds / 3600;
hours = total_hours_int;
total_m = (total_h - total_hours_int) * 60;
total_minutes_int = (total_h - total_hours_int) * 60;
minutes = total_minutes_int;
total_s = ((double)total_m - total_minutes_int) * 60;
seconds = ((double)total_m - total_minutes_int) * 60;
//seconds = (double)total_s;
std:: cout << hours;
std:: cout << minutes;
std:: cout << total_s;
std:: cout << seconds;
}
Output : 143029
Update:
The answer below was given before the C++98 tag was added to the question.
The chono library is available since C++11, so you can use it only from that version onwards.
You haven't given any context for this task.
My asnwer below assumes you need to solve the problem in any valid C++ manner (i.e. that it is not mandatory the caculate the numbers "by hand").
If this is the case, you can use the C++ chrono library for that, as shown below. This solution is shorter and less error-prone, and avoids the type issues you had altogether.
The main class I used is std::chrono::duration and it's helper types (as you can see in the link), as well as std::chrono::duration_cast.
#include <iostream>
#include <chrono>
int main()
{
int total_seconds = 3870;
std::chrono::seconds total_secs(total_seconds);
auto hours = std::chrono::duration_cast<std::chrono::hours>(total_secs);
auto mins = std::chrono::duration_cast<std::chrono::minutes>(total_secs - hours);
auto secs = std::chrono::duration_cast<std::chrono::seconds>(total_secs - hours - mins);
std::cout << "totals seconds: " << total_secs.count() << std::endl;
std::cout << " hours: " << hours.count() << std::endl;
std::cout << " minutes: " << mins.count() << std::endl;
std::cout << " seconds: " << secs.count() << std::endl;
}
Output:
totals seconds: 3870
hours: 1
minutes: 4
seconds: 30
I've reopened answear since it was updated to C++98.
Before C++11 it can be done nicely using standard library:
#include <iostream>
#include <string>
#include <ctime>
int main()
{
int seconds;
while (std::cin >> seconds) {
std::tm t = {};
t.tm_sec = seconds;
t.tm_mday = 1;
mktime(&t);
t.tm_hour += t.tm_yday * 24;
char buf[32];
strftime(buf, sizeof(buf), "%H:%M:%S", &t);
std::cout << t.tm_yday << ' ' << seconds << " = " << buf << '\n';
}
return 0;
}
https://godbolt.org/z/ceWWfoP6P
How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?
C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
Windows uses a different epoch and time units: see
Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))
For a given duration of 203443 milliseconds (this is 3 minutes, 23 seconds and 443 milliseconds), a pattern like e.g.
This took about' m 'minutes and' s 'seconds.
would produce the following
formatted output:
This took about 3 minutes and 23 seconds.
It is different from format timestamp to current date-time. Is there any C++ standard Library (under C++14) or a solution that I can follow. I'm new to C++.
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto d = 203443ms;
auto m = duration_cast<minutes>(d);
d -= m;
auto s = duration_cast<seconds>(d);
std::cout << "This took about " << m.count() << " minutes and "
<< s.count() << " seconds.\n";
}
So I'm trying to make a program that takes some random number of entered seconds and converts it to Days, Hours, Minutes, and Seconds. I had to use symbolic constants to define the hours in a day, minutes in an hour, and seconds in a minute. I passed the value through but it's not being recieved so I end up with some huge negative number. Here's the code. If anyone can tell me where the problem lies I would be ever thankful.
I used the random bit of code in the function definitions code to oput total seconds to see if it was being recieved and it's not.
#ifndef SECONDS_H_
#define SECONDS_H_
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
#include <iostream>
using namespace std;
class Seconds
{
private:
long totalSeconds;
public:
Seconds();
~Seconds(){};
Seconds(int totalSeconds);
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds);
};
#endif
...
#include <conio.h>
#include <string>
#include <iostream>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTE 60
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds)
{
cout << endl;
cout << "Total Seconds: " << totalSeconds;
cout << endl;
days = totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE / HOURS_IN_DAY;
hours = (totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE) % HOURS_IN_DAY;
minutes = (totalSeconds / MINUTES_IN_HOUR) % SECONDS_IN_MINUTE;
seconds = (totalSeconds % SECONDS_IN_MINUTE);
}
...
#include <iostream>
#include <conio.h>
#include <string>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
using namespace std;
int main ()
{
int totalSeconds;
int days = 0, hours = 0, minutes = 0, seconds = 0;
cout << "Enter a random massive amount of seconds: ";
cin >> totalSeconds;
Seconds sec(totalSeconds);
sec.convertSeconds(days, hours, minutes, seconds);
cout << "That is equivalent to " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds." << endl;
cout << "Press any key to continue...";
cin.sync();
_getch();
return 0;
}
This is a problem:
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
The function parameter totalSeconds shadows the class member, so this code is like doing x = x;, it has no effect on this->totalSeconds.
To fix this either use different variable name, or preferably use constructor initialization syntax:
Seconds::Seconds(long totalSeconds)
: totalSeconds(totalSeconds)
{
}
In this version, shadowing does not occur because the constructor initialization lists are smart.
Have you considered that the problem might be Integer Overflow?
This will show how many seconds:
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
int times,timed;
times=time(NULL);
//CODE HERE
timed=time(NULL);
times=timed-times;
cout << "time from start to end" << times;
}
This will show how many ticks:
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
int times,timed;
times=clock();
//CODE HERE
timed=clock();
times=timed-times;
cout << "ticks from start to end" << times;
}
How do I get milliseconds?
Refer to question "Convert Difference between 2 times into Milliseconds" on Stack Overflow.
Or use this:
static double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
return diffms;
}
If you use a Unix OS, like Linux or Mac OS X, you can go to the command line and use the line
time call-program
The time command times how long the execution of any command line takes, and reports that to you.
I don't know if there's something like that for Windows, nor how you can measure miliseconds inside a C/C++ program, though.
There's a CLOCKS_PER_SEC macro to help you convert ticks to milliseconds.
There are O/S-specific APIs to get high-resolution timers.
You can run your program more than once (e.g. a 1000 times) and measure that using a low-resolution timer (e.g. some number of seconds), and then divide that total by the number of times you ran it to get a (higher-resolution) average time.
In Windows, you can use GetTickCount, which is in milliseconds.
Under Win32, you can access the high-resolution timer using QueryPerformanceFrequency and QueryPerformanceCounter (IMHO that should be preferred, possibly with fallback to GetTickCount). You can find the example in Community Content section on MSDN.
This will show how many ticks:
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
int times,timed;
times=clock();
//CODE HERE
timed=clock();
times=timed-times;
cout << "ticks from start to end" << times;
}
How do I get milliseconds?
clock() returns milliseconds. Compile this code, it will return 1000. Of course if your on Linux and not on Windows replace #include <windows.h> with #include <unistd.h> and replace Sleep(1000) with usleep(1000000).
#include <stdio.h>
#include <time.h>
#include <windows.h>
int main()
{
unsigned long x = clock();
Sleep(1000);
printf("Difference: %d", clock() - x);
}
Below C++ program calculates the time elapsed for a simple code in milliseconds, microseconds, nanoseconds, and seconds. It includes the <chrono.h> header which provides access to the current time using system_clock(). The system_clock() is designed to represent the real-time and used by all processes running on the system.
Code:
#include <iostream>
#include <chrono>
#include <unistd.h>
using namespace std;
int main() {
auto start = chrono::steady_clock::now();
sleep(2);
auto end = chrono::steady_clock::now();
cout << "Elapsed time in microseconds: "
<< chrono::duration_cast<chrono::microseconds>(end - start).count()
<< " µs" << endl;
cout << "Elapsed time in milliseconds: "
<< chrono::duration_cast<chrono::milliseconds>(end - start).count()
<< " ms" << endl;
cout << "Elapsed time in nanoseconds: "
<< chrono::duration_cast<chrono::nanoseconds>(end - start).count()
<< " ns" << endl;
cout << "Elapsed time in seconds: "
<< chrono::duration_cast<chrono::seconds>(end - start).count()
<< " sec";
return 0;
}
Output:
Elapsed time in microseconds: 2000127 µs
Elapsed time in milliseconds: 2000 ms
Elapsed time in nanoseconds: 2000127736 ns
Elapsed time in seconds: 2 sec