简体   繁体   中英

Seconds to Days, Hours and Minutes (customizable day length)

I have a loop and in every loop I get the current seconds the application has been running for I then want to convert this time into how many, Days, Hours and Seconds that the seconds calculate to but not 'real time' I need to be able to customize how many seconds are in a day, I have tried examples on SO and the web but nothing seems to be out there for this. I have some defines

#define DAY             1200
#define HOUR            DAY / 24
#define MINUTE          HOUR / 60
#define SECOND          MINUTE / 60

So in my define a day would last for 1200 seconds. I have then been trying to convert elapsed seconds into 'my' seconds

seconds_passed = fmodf(SECOND, (float)(GetTicks() / 1000));

Which returns what SECOND equals (0.013889) but then every loop is the same, it never changes I was thinking I would just be able to convert for example: 1real second into 1.25fake seconds then

Minute = (seconds_passed / MINUTE);
seconds_passed = fmodf(seconds_passed, MINUTE);

work out how many (fake)minutes, (fake)hours and (fake)days have elapsed since the application started.

Hope that makes sense, thank you for your time.

Since you want to customise how many seconds are in a day, all you're really doing is changing the ratio of 1 second : 1 second.

For instance, if you did was 1200 seconds in a day your ratio is:
1:72
that is, for every 1 second that passes in your day, it is the equivilent of 72 real seconds.

So yes basically all you need to do in your program is find the ratio of 1 second to 1 second, times your elapsed seconds by that to get the 'fake' seconds, and then use that value... The code may look something like this:

// get the ratio second:fake_second
#define REAL_DAY_SECONDS 86400
int ratio = REAL_DAY_SECONDS / DAY;

fake_to_real = fake_second*ratio;
real_to_fake = real_second/ratio;

You can make your own time durations with one line in chrono:

using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>; 

Some sample code

#include <iostream>
#include <chrono>
using namespace std::chrono_literals;

using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>;
 
int main()
{
    auto f_x = fake_seconds(350s);
    std::cout << "350 real seconds are:\n" << f_x.count() << " fake_seconds\n";
}

https://godbolt.org/z/f5G86avxr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM