display the time using time.h header file - c++

I want to display the time of invoking a function.
that is
void DrawableGameComponent::Update() {
time_t result = time(NULL);
cout << " Updated # " << asctime(localtime(&result));
}
its working fine, it gives the output of date, month, year along with the time. How can I make it to get the time only..
it should display only hours:minutes:seconds.
also the time of invocation should be past as an argument from another member function of another class.that is
void Run();
Any idea to get it please.

Try like this maybe:
char myTime[12];
time_t now = time(0);
strftime(myTime, sizeof(myTime), "%H:%M:%S", localtime(&now));
cout << " Updated # " << myTime;

Related

Getting Current Date inside a C++ process running 24*7

I have a backend process running 24*7 mostly built using C++ and I need to validate if an input date (in format YYYYMMDD) belongs in a set of next 5 business days. The input date is not a clear indicator of the current date so I am using the following function to get the current date and then calculating the next 5 business days from it.
const std::string& CurrentDateStr() {
static const std::string sDate = []() {
time_t currTime = time(NULL);
struct tm timeinfo;
localtime_r(&currTime, &timeinfo);
char buffer[16]="";
strftime(buffer, sizeof(buffer), "%Y%m%d", &timeinfo);
return std::string(buffer);
} ();
return sDate;
}
This function returns me the correct current date if the process was started today but if the process continues running till tomorrow then it will return me yesterday's date as current date due to which calculation of next 5 business days from current date goes for a toss.
Is this expected ? Is there some workaround for it or is there a better way to implement the requirement using standard C++
Your issue is the static variable. You should read up on that, because you're going to encounter it a lot. This is what the comments were trying to get you to do. You can fix your issue by just removing it:
const std::string& CurrentDateStr() {
time_t currTime = time(NULL);
struct tm timeinfo;
localtime_r(&currTime, &timeinfo);
char buffer[16]="";
strftime(buffer, sizeof(buffer), "%Y%m%d", &timeinfo);
return std::string(buffer);
}
For a more modern solution, as suggested in the comments as well, read up on chrono. Especially system_clock::now().
one way to do it using chrono:
#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
int main()
{
while (true)
{
theTime currentTime = time(nullptr);
tm* date = gmtime(&currentTime);
// Print the date and time
std::cout << "Current date and time: " << date->theDay << "/" << date->theMon + 1 << "/" << date->theYear + 1900;
std::cout << " " << date->theHour << ":" << date->theMmin << ":" << date->theSec << std::endl;
// Wait for 1 minute
std::this_thread::sleep_for(std::chrono::minutes(1));
}
}
OR Use the sleep method.
#include <iostream>
#include <ctime>
#include <unistd.h>
int main()
{
while (true)
{
time_t currentTime = time(nullptr);
tm* date = gmtime(&currentTime);
std::cout << "Current date and time: " << date->tm_mday << "/" << date->tm_mon + 1 << "/" << date->tm_year + 1900;
std::cout << " " << date->tm_hour << ":" << date->tm_min << std::endl;
// Wait for 1 minute (60 seconds)
sleep(60);
}
}

gmtime is giving me some times localtime?

I'm printing events in a multi-thread environment the console is a static mutex shared by all the threads.
The problem is randomly every hundred or thousand events the time I get is local time and not UTC.
I have seen this error just in Linux machines (build with g++) but not in Windows (build VC++). I have no clue where I could start, any idea?
void Publish(std::string source, std::string topic, std::string msg) NOEXCEPT {
console.lock();
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
char buf[50];
strftime(buf, sizeof (buf), "%Y-%m-%dT%H:%M:%S+00:00", gmtime(&now));
cout << buf << " " << source << " " << topic << " " << msg << endl;
cout.flush();
console.unlock();
}
struct tm * gmtime (const time_t * timer);
Converts time_t to tm as UTC time. This call uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone).
This must be working correctly.
However, not sure about this:
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
Is your *localtime giving the current time accurately under multithreaded situation? Is it a shared variable?
Instead could you use the following:
std::time_t now = time(0);

How do i use tm structure to add minutes to current time?

Currently I am trying to add minutes to current time, but how do I do it? I read through some tutorials and all but still have no idea how to do it.
So my code goes..
time_t now = time(0);
tm* localtm = localtime(&now);
cout << "Current time : " << asctime(localtm) << endl;
My program will sort of "run" in minutes which is + 1 minute every loop..
So lets say there is 255 loops and it is 255 minutes.. I store it in Minute.
I tried adding it this way but the time remained the same as the current time..
localtm->tm_min + Minute;
mktime (localtm);
cout << "End of program time : " << asctime(localtm) << endl;
I am wondering how should I do it. Can anyone help?
int main()
{
time_t now = time(0);
size_t Minutes = 255;
time_t newTime = now + (60 * Minutes);
struct tm tNewTime;
memset(&tNewTime, '\0', sizeof(struct tm));
localtime_r(&newTime, &tNewTime);
cout << asctime(&tNewTime) << endl;
}
C++ 11:
int main(int argc,char* argv[])
{
std::chrono::system_clock::time_point time_now =
std::chrono::system_clock::now();
time_now += std::chrono::hours(10);
time_t c_time_format = std::chrono::system_clock::to_time_t(time_now);
std::string str_time = std::ctime(& c_time_format);
std::cout<<str_time<<std::endl;
return 0;
}
To compile this code ,you shoud include headrs chrono ctime .
You can use "seconds(val),minutes(val),hours(val) etc"
With any question,you can visit the following :
http://www.cplusplus.com/reference/chrono/system_clock/

How to split the date and time in C++?

I'm trying to make a program wherein the user will input his/her birthday and the program will compute how many days, months, years, hours and minutes they've lived.
I've searched Google and I see there's a way to split the date into three to four parts.
I've copied this code and it seems to be working. It's just that I don't understand it. All the forums I've read don't help much either. Can anyone explain it to me?
time_t t = time(NULL);
tm* timePtr = localtime(&t);
cout << "seconds= " << timePtr->tm_sec << endl;
cout << "minutes = " << timePtr->tm_min << endl;
cout << "hours = " << timePtr->tm_hour << endl;
cout << "day of month = " << timePtr->tm_mday << endl;
cout << "month of year = " << timePtr->tm_mon << endl;
cout << "year = " << timePtr->tm_year + 1900 << endl;
cout << "weekday = " << timePtr->tm_wday << endl;
cout << "day of year = " << timePtr->tm_yday << endl;
cout << "daylight savings = " << timePtr->tm_isdst << endl;
In most computing environments, dates and times are a unified concept. The C runtime library (hence also C++) provides the type time_t which measures time (and dates) as the number of seconds since 1970-01-01T00:00:00 UTC.
The localtime() function takes a time_t and converts that into the calendar-like fields which humans are accustomed to, according to the local timezone (which is obtained from the computer—the timezone can also be specified specifically). There is another very similar call, gmtime() which does not consider the local timezone, but always uses the UTC timezone, formerly called GMT.
To do what you want, accept from the user their birth date, birth time, and timezone, and convert that into a time_t. Then subtract that from the current time() value. The difference is the number of seconds they have been alive. To be friendly, use gmtime() to convert that to years, months, days, hours, minutes, and seconds.
This is not standard C++ code. This is (also) POSIX code.
(The recent C++11 standard gives you <chrono> but few compilers implement it; on Linux you'll need GCC 4.6 or 4.7; there is also <ctime>)
See this answer to a question very related to yours.
As for time, gettimeofday, localtime, strftime they have well written reference documentation in the manual page. What don't you understand?
(follow the links I gave you and read the linked pages carefully).

C++: how to get the actual time with time and localtime?

I'm looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for time and localtime. However, it seems like the localtime function is a little tricky, since it says:
All calls to localtime and gmtime use the same static structure, so
each call overwrites the results of the previous call.
The problem that this causes is shown in the next snippet of code:
#include <ctime>
#include <iostream>
using namespace std;
int main() {
time_t t1 = time(0); // get time now
struct tm * now = localtime( & t1 );
std::cout << t1 << std::endl;
sleep(2);
time_t t2 = time(0); // get time now
struct tm * now2 = localtime( & t2 );
std::cout << t2 << std::endl;
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday << ", "
<< now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec
<< endl;
cout << (now2->tm_year + 1900) << '-'
<< (now2->tm_mon + 1) << '-'
<< now2->tm_mday << ", "
<< now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec
<< endl;
}
A typical output for this is:
1320655946
1320655948
2011-11-7, 9:52:28
2011-11-7, 9:52:28
So as you can see, the time_t timestamps are correct, but the localtime messes everything up.
My question is: how do I convert a timestamp ot type time_t into a human-readable time?
If you are worried about reentrancy in localtime and gmtime, there is localtime_r and gmtime_r which can handle multiple calls.
When it comes to formatting the time to your liking, check the function strftime.
the localtime() call stores the results in an internal buffer.
Every time you call it you overwrite the buffer.
An alternative solution would be to make a copy of the buffer.
time_t t1 = time(0); // get time now
struct tm* now = localtime( & t1 ); // convert to local time
struct tm copy = *now; // make a local copy.
// ^^^ notice no star.
But note: The only time you should be converting to local time is when you display the value. At all other times you should just keep the time as UTC (for storage and manipulation). Since you are only converting the objects for display convert then print immediately and then things will not go wrong.
localtime has what is best considered a legacy interface. It can't be
used in multithreaded code, for example. In a multithreaded
environment, you can use localtime_r under Posix or localtime_s
under Windows. Otherwise, all you have to do is save the results:
tm then = *localtime( &t1 );
// ...
tm now = *localtime( &t2 );
It would probably be more idiomatic, however, to only call localtime
immediately before formatting the output, e.g.:
std::string
timestampToString( time_t timeAndDate )
{
char results[100];
if ( strftime( results, sizeof( results ), "%Y-%m-%d, %H:%M:%S",
localtime( &timeAndDate) ) == 0 ) {
assert( 0 );
}
return results;
}
and then writing:
std::cout << formatTime( t1 ) << std::endl;
(You could also create a more generic formatting function, which took
the format as an argument.)
You can run continuous clock using following code. It works nicely.
#include<iostream>
#include <Windows.h>
#include<ctime>
using namespace std;
void main() {
while(true) {
system("cls"); //to clear screen
time_t tim;
time(&tim);
cout << ctime(&tim);
Sleep(1);
}
}