I know, this particular kind of thing has been answered a number of times, but I think, my question here is more to do with general C++ stuff than ctime()
or date/time conversion. I just happened to try it out with this. So, here is the code:
#include <iostream>
#include <ctime>
using std::cout;
using std::endl;
using std::string;
void strTime( int iM, int iD, int iY )
{
time_t rwTime;
time( &rwTime ); // current epoch time
// 1st set:: using tmInfo_11
struct tm *tmInfo_11;
tmInfo_11 = localtime( &rwTime );
tmInfo_11->tm_mon = iM - 1;
tmInfo_11->tm_mday = iD;
tmInfo_11->tm_year = iY - 1900;
mktime( tmInfo_11 );
cout << "tmInfo_11 RESULt: " << tmInfo_11->tm_wday << endl;
// 2nd set:: using tmInfo_22 //
struct tm tmInfo_22;
tmInfo_22 = *localtime( &rwTime );
tmInfo_22.tm_mon = iM - 1;
tmInfo_22.tm_mday = iD;
tmInfo_22.tm_year = iY - 1900;
mktime( &tmInfo_22 );
cout << "tmInfo_22 RESULt: " << tmInfo_22.tm_wday << endl;
}
int main()
{
int iMM=12, iDD=9, iYY=2009;
strTime( iMM, iDD, iYY );
}
and my question is: What's the difference between these 2 sets of code? Either way, I can achieve the same thing. The notable difference is the first 2-lines from the each set and I have to admit that I didn't understand all of it. So, can anyone kindly explain it to me please? Also, dose one have any advantage(s)/disadvantage(s) over other? Cheers!!
Just for the sake of completeness, this the code I ended up with, which gives me the desired result. So, basically it's for the future reference:
#include <iostream>
#include <fstream>
#include <ctime>
using std::cout;
using std::endl;
using std::string;
tm testTime( int iM, int iD, int iY );
int main()
{
char tmBuff[20];
int iMM=12, iDD=9, iYY=2009;
tm myDate = testTime( iMM, iDD, iYY );
strftime( tmBuff, sizeof(tmBuff), "%a, %b %d, %Y", &myDate );
cout << "TESt PRINt TIMe: " << tmBuff << endl;
}
tm testTime( int iM, int iD, int iY )
{
time_t rwTime;
struct tm tmTime;
tmTime = *localtime( &rwTime );
tmTime.tm_mon = iM - 1;
tmTime.tm_mday = iD;
tmTime.tm_year = iY - 1900;
mktime( &tmTime );
return tmTime;
}
NOTE that it does require the *localtime( &rwTime )
to be specified (even though tmTime is getting overwritten afterwards) otherwise the Year(%Y) in the strftime()
doesn't work. Thanks to all for helping. Cheers!!