strptime 函数是 POSIX 标准中定义的,在 Windows 上不是标准 C 库的一部分。
下面手动实现字符串转时间格式
#include <stdio.h>
#include <time.h>
int main() {
const char *dateString = "2023-11-10 09:50:30";
struct tm tmStruct;
int year, month, day, hour, minute, second;
// 使用 sscanf 解析字符串
// 如果解析成功,sscanf 会返回成功匹配的字段数量,这里是 6。
// 如果解析失败,返回值会小于 6。你可以根据返回值来判断解析是否成功。
if (sscanf(dateString, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second) == 6) {
// 提取成功,填充到 tmStruct 结构中
tmStruct.tm_year = year - 1900; // 年份需要减去 1900
tmStruct.tm_mon = month - 1; // 月份从 0 开始
tmStruct.tm_mday = day;
tmStruct.tm_hour = hour;
tmStruct.tm_min = minute;
tmStruct.tm_sec = second;
// 打印结果
printf("Year: %d, Month: %d, Day: %d\n", tmStruct.tm_year + 1900, tmStruct.tm_mon + 1, tmStruct.tm_mday);
printf("Hour: %d, Minute: %d, Second: %d\n", tmStruct.tm_hour, tmStruct.tm_min, tmStruct.tm_sec);
} else {
// 提取失败
printf("Failed to extract date and time from the string.\n");
}
// 转换为时间戳
time_t timestamp = mktime(&tmStruct);
printf("Timestamp: %ld\n", timestamp);
// 要验证时间的正确性,只需把时间戳转换为struct tm
struct tm *localTimeInfo = localtime(×tamp);
printf("Year: %d\n", localTimeInfo->tm_year + 1900); // tm_year 表示自 1900 年起的年数
printf("Month: %d\n", localTimeInfo->tm_mon + 1); // tm_mon 表示月份(0 到 11)
printf("Day: %d\n", localTimeInfo->tm_mday); // tm_mday 表示月中的天数
printf("Hour: %d\n", localTimeInfo->tm_hour); // tm_hour 表示小时
printf("Minute: %d\n", localTimeInfo->tm_min); // tm_min 表示分钟
printf("Second: %d\n", localTimeInfo->tm_sec); // tm_sec 表示秒
return 0;
}
参考资料: