Question

I'm using C++ under Linux compiling with standard GCC. In my program I want to add a simple clock showing HH:MM:SS. What's the easiest way to do that?

Was it helpful?

Solution

A good way is to use localtime

OTHER TIPS

You can make use of localtime along with strftime.

Working link

My quick-and-dirty solution:

// file now.cc
#include <iostream>
#include <iomanip>
#include <ctime>

using namespace std;

int main()
{
    time_t ct = time(0);
    struct tm* currtime = localtime(&ct);
    cout << setfill('0') << setw(2) << currtime->tm_hour << ":"
         << setw(2) << currtime->tm_min << ":"
         << setw(2) << currtime->tm_sec << endl;
    return 0;
}

This also does zero-padding (which you probably want).

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}
int main()
{
    time_t myTime;

    while(1)
    {
        time(&myTime);
        printf("%s", asctime(gmtime(&myTime)));
        delay(1000);
        system("cls");
    }
    return 0;
}

The easiest way?

system("date +%T");

Look at getTimeStamp() you can adjust this to any format you want

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top