Trying to multiple time

what I am trying to do is:

10:00
14:00
18:00
22:00

Increment the current time by 4 hours each loop but I currently get

Fri Sep 29 23:04:54 2017
Sun Jun 28 23:09:49 2065
Wed Mar 29 00:14:44 2113
Fri Dec 26 01:19:39 2160

I understand it's a little messy, I am just trying to work this out but it's a little more complicated than I thought. Any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    time_t now = time(0);
    size_t minutes = 60;
    time_t t = 0;

    int hours = 4;
    int counter = 4;

    time_t start_time = now + (60 * minutes);

    for (int i = 0; i < counter; ++i)
    {
        std::cout << std::asctime(std::localtime(&start_time)) << std::endl;

        start_time += now + (60 * minutes) * counter+1;
    }
Last edited on
Line 14
start_time += now + (60 * minutes) * counter+1;
If you have += now here then the times rapidly become enormous.

You have a lot of stray and unnecessary variables, and you are completely confusing "now" and "start_time", but I suspect you wanted line 14 to look something like
start_time += hours * minutes * 60;

I've no idea why line 8 isn't simply
time_t start_time = time(0);


I'm not sure about portability, I'm afraid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
   time_t t = time( 0 );
   int hours = 4;
   for ( int i = 0; i < 4; i++ )
   {
      cout << asctime( localtime( &t ) );
      t += hours * 3600;
   }
}
Fri Sep 29 22:53:12 2017
Sat Sep 30 02:53:12 2017
Sat Sep 30 06:53:12 2017
Sat Sep 30 10:53:12 2017
Last edited on
Yea I really apologise for the messy code. I come from a Ruby & Python background.

A lot of that code was just "testing" I should have tidied it up.

What you did is very elegant, it works exactly as I needed and now looking at it;

t += hours * 3600;

^ this for example, I actually facepalmed myself. I just didn't see the simplicity.

I am very grateful for your help, you've no idea how long I've been trying to figure this one out. I am a beginner and loving it :)
Topic archived. No new replies allowed.