MySQL中的datetime類型可以存儲(chǔ)日期和時(shí)間,其格式為:YYYY-MM-DD HH:MM:SS
在C語言中使用MySQL C API訪問數(shù)據(jù)庫,可以通過以下代碼將時(shí)間轉(zhuǎn)換為MySQL datetime格式:
#include <time.h> #include <mysql.h> MYSQL_TIME datetime; struct tm timeinfo; char time_str[20]; time(&now); localtime_r(&now, &timeinfo); datetime.year = timeinfo.tm_year + 1900; datetime.month = timeinfo.tm_mon + 1; datetime.day = timeinfo.tm_mday; datetime.hour = timeinfo.tm_hour; datetime.minute = timeinfo.tm_min; datetime.second = timeinfo.tm_sec; mysql_datetime_to_str(&datetime, time_str, sizeof(time_str));
其中,time()函數(shù)獲取當(dāng)前時(shí)間,localtime_r()函數(shù)將當(dāng)前時(shí)間轉(zhuǎn)換為struct tm結(jié)構(gòu)體,mysql_datetime_to_str()函數(shù)將struct tm轉(zhuǎn)換為MySQL datetime格式的字符串。
可以通過以下代碼將MySQL datetime格式的字符串轉(zhuǎn)換為struct tm結(jié)構(gòu)體:
char time_str[20]; MYSQL_TIME datetime; struct tm timeinfo; mysql_parse_datetime(&datetime, time_str, strlen(time_str)); timeinfo.tm_year = datetime.year - 1900; timeinfo.tm_mon = datetime.month - 1; timeinfo.tm_mday = datetime.day; timeinfo.tm_hour = datetime.hour; timeinfo.tm_min = datetime.minute; timeinfo.tm_sec = datetime.second; timeinfo.tm_isdst = -1; time_t time = mktime(&timeinfo);
其中,mysql_parse_datetime()函數(shù)將MySQL datetime格式的字符串轉(zhuǎn)換為MYSQL_TIME結(jié)構(gòu)體,再通過mktime()函數(shù)將struct tm轉(zhuǎn)換為time_t格式。