在c++開(kāi)發(fā)中,有時(shí)候會(huì)提示localtime() unsafe,這時(shí)候就可以使用localtime_s()來(lái)替換。
錯(cuò)誤:C4996
'localtime': This function or variable may be unsafe.
Consider using localtime_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details。
法一:在文件中針對(duì)隨后內(nèi)容關(guān)閉警告。(直接關(guān)閉警告不理會(huì),但可能會(huì)出錯(cuò)?。?/p>
#pragma warning(disable : 4996)
法二:用localtime_s()替換
//先看源碼
#if __STDC_WANT_SECURE_LIB__
_Check_return_wat_
static __inline errno_t __CRTDECL ctime_s(
_Out_writes_(_SizeInBytes) _Post_readable_size_(26) char* const _Buffer,
_In_range_(>=,26) size_t const _SizeInBytes,
_In_ time_t const* const _Time
)
{
return _ctime64_s(_Buffer, _SizeInBytes, _Time);
}
_Check_return_wat_
static __inline errno_t __CRTDECL gmtime_s(
_Out_ struct tm* const _Tm,
_In_ time_t const* const _Time
)
{
return _gmtime64_s(_Tm, _Time);
}
_Check_return_wat_
static __inline errno_t __CRTDECL localtime_s(
_Out_ struct tm* const _Tm,
_In_ time_t const* const _Time
)
{
return _localtime64_s(_Tm, _Time);
}
#endif
淺說(shuō)一下上面三個(gè)函數(shù):
1、ctime_s():將給定時(shí)間轉(zhuǎn)換為當(dāng)?shù)厝諝v,轉(zhuǎn)換為文本表示。
2、gmtime_s():將歷元以來(lái)的給定時(shí)間轉(zhuǎn)換為日歷時(shí)間。將結(jié)果存儲(chǔ)在靜態(tài)存儲(chǔ)器中,返回指向該靜態(tài)存儲(chǔ)器的指針。
3、localtime_s():將歷元以來(lái)的給定時(shí)間轉(zhuǎn)換為以本地時(shí)間表示的日歷時(shí)間。將結(jié)果存儲(chǔ)在靜態(tài)存儲(chǔ)器中,返回指向該靜態(tài)存儲(chǔ)器的指針。
//下面是日期參數(shù)
struct tm
{
int tm_sec; // seconds after the minute - [0, 60] including leap second
int tm_min; // minutes after the hour - [0, 59]
int tm_hour; // hours since midnight - [0, 23]
int tm_mday; // day of the month - [1, 31]
int tm_mon; // months since January - [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday - [0, 6]
int tm_yday; // days since January 1 - [0, 365]
int tm_isdst; // daylight savings time flag
};
示例:
//strftime(...)中第三個(gè)參數(shù)控制格式,可以根據(jù)具體需要調(diào)整。
//用localtime()獲取當(dāng)前時(shí)間
time_t ticks = time(NULL);
struct tm* p_Time = localtime(&ticks);
char c_TimeStamp[64];
memset(c_TimeStamp, 0 ,sizeof(c_TimeStamp));
strftime(c_TimeStamp, sizeof(c_TimeStamp), "%Y-%m-%d %H:%M:%S", p_Time);
cout<
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧
文章名稱(chēng):用localtime-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)源:http://aaarwkj.com/article4/gesoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、App設(shè)計(jì)、自適應(yīng)網(wǎng)站、小程序開(kāi)發(fā)、定制網(wǎng)站、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容