Date and time keeping

Hey everybody,
Im going to start working on a program that relies heavily on one second ticks along with keeping track what day it is. I was wondering on how i would i be able to get the current time, when a second has passed, and what day it is. Could anybody give any examples?
Thanks in advance :)
Most of this will require the ctime library or something similar.
http://cplusplus.com/reference/clibrary/ctime/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  time_t TheTime; // declare a time object
  time(&TheTime); // Get the current time
  
  cout << TheTime << " seconds have passed since January 1, 1970" << endl;
  
  struct tm * timeinfo; // This will hold the time in an easy-to-use structure
  timeinfo = localtime ( &TheTime ); // This converts from raw time to the structure.

  cout << "Current time: " << timeinfo->tm_hour << ':' 
                           << timeinfo->tm_min  << ':' 
                           << timeinfo->tm_sec << endl;

  cout << "Current date (DD/MM/YYYY): " << timeinfo->tm_mday  << '/' 
                                        << timeinfo->tm_mon+1 << '/' 
                                        << timeinfo->tm_year+1900 << endl;

  return 0;
}
1349899651 seconds have passed since January 1, 1970
Current time: 21:50:31
Current date (DD/MM/YYYY): 10/10/2012


If you want to do something every second, you'll need to interface with your OS directly with a callback function or do something with another library. I like Qt's QTimer class (http://qt-project.org/doc/qt-4.8/QTimer.html), but you need to have the SDK installed. In here the function update() will be called in 1000ms and will be called again every 1000ms after that until the program is exited:
1
2
3
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);


Edit: Does anyone know if there's a boost equivalent to QTimer that will call-back a function every X ms or single-shot after X ms? I was looking in boost:signals, but that didn't seem to be the right place.
Last edited on
Take a look at the examples on these pages:
http://www.cplusplus.com/reference/clibrary/ctime/

Edit:
=/
Last edited on
Ninja!!!
Topic archived. No new replies allowed.