我知道,这种特殊的事情已经被回答了很多次,但我认为,我的问题更多的是与一般 C++ 的东西有关,而不是ctime()
日期/时间转换。我只是碰巧用这个试了一下。所以,这里是代码:
#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 );
}
我的问题是:这两组代码有什么区别?无论哪种方式,我都可以实现同样的目标。显着的区别是每组的前两行,我不得不承认我没有全部理解。那么,任何人都可以向我解释一下吗?此外,第一剂与其他剂相比有什么优势/劣势?干杯!!
只是为了完整起见,这是我最终得到的代码,它给了我想要的结果。所以,基本上它是为了将来参考:
#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;
}
请注意,它确实需要*localtime( &rwTime )
指定 (即使 tmTime 之后被覆盖),否则 中的 Year(%Y)strftime()
不起作用。感谢大家的帮助。干杯!!