開發環境vc2013,本人有個寫資料庫函式,需要反復將時間資料寫入資料庫中,用了別人寫的c檔案time_util.c,該檔案中有函式使用到了localtime,原來是:
time_t timeT = (time_t)second;
struct tm *ptime;
ptime=localtime(&timeT);
運行中發現,隨著不斷回圈寫入,程式容易崩潰,原因是ptime有時候經常回傳為NULL;
網上查找,可能是localtime函式問題,遂改成
time_t timeT = (time_t)second;
struct tm ptime;
localtime_s(&ptime, &timeT);
編譯是出現LNK2028,LNK2019和LNK1120錯誤
錯誤 8 error LNK2028: 無法決議的標記(0A00000F) "extern "C" int __cdecl localtime_s(struct tm * const,__int64 const * const)" (?localtime_s@@$$J0YAHQAUtm@@QB_J@Z),該標記在函式 "extern "C" void __cdecl unix_to_date(unsigned __int64,char *)" (?unix_to_date@@$$J0YAX_KPAD@Z) 中被參考 D:\正在試驗\舞臺測驗\MultiProbesMFCApping徠卡(資料庫成功后修改0807)\MFCApp\time_util.obj MFCApp
錯誤 9 error LNK2019: 無法決議的外部符號 "extern "C" int __cdecl localtime_s(struct tm * const,__int64 const * const)" (?localtime_s@@$$J0YAHQAUtm@@QB_J@Z),該符號在函式 "extern "C" void __cdecl unix_to_date(unsigned __int64,char *)" (?unix_to_date@@$$J0YAX_KPAD@Z) 中被參考 D:\正在試驗\舞臺測驗\MultiProbesMFCApping徠卡(資料庫成功后修改0807)\MFCApp\time_util.obj MFCApp
實在找不到原因,求各位大神幫忙看看
uj5u.com熱心網友回復:
https://zh.cppreference.com/w/c/chrono/localtimeuj5u.com熱心網友回復:
// crt_localtime_s.c
/* This program uses _time64 to get the current time
* and then uses _localtime64_s() to convert this time to a structure
* representing the local time. The program converts the result
* from a 24-hour clock to a 12-hour clock and determines the
* proper extension (AM or PM).
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
int main( void )
{
struct tm newtime;
char am_pm[] = "AM";
__time64_t long_time;
char timebuf[26];
errno_t err;
// Get time as 64-bit integer.
_time64( &long_time );
// Convert to local time.
err = _localtime64_s( &newtime, &long_time );
if (err)
{
printf("Invalid argument to _localtime64_s.");
exit(1);
}
if( newtime.tm_hour > 12 ) // Set up extension.
strcpy_s( am_pm, sizeof(am_pm), "PM" );
if( newtime.tm_hour > 12 ) // Convert from 24-hour
newtime.tm_hour -= 12; // to 12-hour clock.
if( newtime.tm_hour == 0 ) // Set hour to 12 if midnight.
newtime.tm_hour = 12;
// Convert to an ASCII representation.
err = asctime_s(timebuf, 26, &newtime);
if (err)
{
printf("Invalid argument to asctime_s.");
exit(1);
}
printf( "%.19s %s\n", timebuf, am_pm );
}
uj5u.com熱心網友回復:

c 函式 多執行緒不安全吧。資料庫時間的話 直接用now() 內置函式不行?
uj5u.com熱心網友回復:
直接調Windows api GetLocalTimeuj5u.com熱心網友回復:
localtime_s 的代碼是開放的, 如果找不到庫,就照搬代碼寫一份uj5u.com熱心網友回復:
localtime_s, _localtime32_s, _localtime64_s <time.h> <ctime> or <time.h>uj5u.com熱心網友回復:
直接資料庫層面可以解決的,sqlserver設定欄位為datetime,默認為getdate()即可,不用insert這個欄位,只要寫資料就自動添加時間。其它資料庫類似。轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/38812.html
標籤:基礎類
