You have to use C time function for getting computer clock’s time.
The basic idea is following:
- Ask the user for “his” time
- In the same time save the computer’s current time
When is time to showing updated current time:
- Check computer current time
- Calculate the users’s current time using previous stored times as a delta
To do this, due to how C “time” function works, I’ve to store in the program the time variables in seconds, so I have to convert hours, minutes and seconds in just one single variable storing seconds.
Here’s the function:
#include <iostream>
#include <conio.h>
#include <time.h>
using namespace std;
class Time {
private:
time_t userTime;
time_t computerTime;
public:
void SetTime(int hour1 = 0, int minute1 = 0, int second1 = 0)
{
userTime = hour1 * 60 * 60 + minute1 * 60 + second1; // Convert input time in seconds.
time(&computerTime); // Get computer's current time.
cout<<"set time working";
}
void display()
{
time_t currentComputerTime;
time(¤tComputerTime); // Get computer's updated current time.
time_t currentUserTime = userTime + (currentComputerTime - computerTime); // Calculate current user's time in seconds.
// Convert time_t variable in hours, minutes and seconds.
int hour = currentUserTime / (60 * 60);
int minute = (currentUserTime / 60) % 60;
int second = currentUserTime % 60;
cout<<"hour | minute | second"<<endl;
cout<<hour<<" "<<minute<<" "<<second;
}
};
int main()
{
Time time;
//char om;
int hour1, minute1,second1;
cout<<"enter the hour,minute,second: ";
cin>>hour1;
cin>>minute1;
cin>>second1;
time.SetTime(hour1,minute1,second1);
char pcz[200];
cout<<"\n The current time?";
cin >> pcz;
time.display();
return 0;
}
1
solved How can I check time in C++?