由于在處理游戲服務端時,必須考慮到使用的處理。在此,使用了boost中的時間相關的內容。
用boost的好處很多,下面是項目中對此的一點應用小結:
1) 支持跨平臺。
2) 時間的精確度極高。取得毫秒級的絕對沒問題。(似乎微秒級的也可以)
3) 用法方便。
using namespace boost::posix_time;
using namespace boost::gregorian;
//using boost::gregorian::date;
#include <boost/date_time/posix_time/posix_time.hpp>
#define BOOST_DATE_TIME_SOURCE
static ptime const epoch(date(1970, 1, 1));//一個基準點。
std::string currtimestamp = CommonHelper::format("%I64u", (WE::uint64)((microsec_clock::universal_time() - epoch).total_milliseconds()));
//提示:
1) microsec_clock::universal_time()是取得格林威治時間。
2) 如果是:microsec_clock::local_time()則取得的是本地時間。
3) 如果想取得北京時間,則只需要加上8小時即可。microsec_clock::universal_time() + hours(8);
4) 上面的語句是計算當前格林威治時間的時間戳。
4) boost::posix_time::ptime 因重載了許多操作符運算。因此,對它的使用就如同基本類型一樣。如:可以很方便計算兩點時間點的差距。
boost::posix_time::ptime pt1(date(xxxx, x, x), time_duration(10, 1, 23));
//上面也可以這樣寫:boost::posix_time::ptime pt1(date(xxxx, x, x), time_duration(hours(10), minutes(1), seconds(23)));
//再比如:boost::posix_time::ptime pt1(date(xxxx, x, x), hours(10));如果想要詳細了解,請自行研究boost源碼。
boost::posix_time::ptime pt2(.....);//這邊的構造函數參數就不寫了。請自行參考上面的語句。
time_duration td = pt1 - pt2;//注意:ptime是不支持 + 的。因為它沒有重載該操作。計算它們的加,是沒有意義的。而 - 有意義。所以可如此操作。
5) 取得日期,取得時間都很方便。
此次,就暫時就寫這么多吧。