嗨,我需要將time包含字串的變數轉換為 time_t 型別,格式為我想在之后列印:
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char time[100];
strftime(time, 100, "%b %d %H:%M", tm);
我不想對上面的代碼進行任何修改并保留我選擇的格式。謝謝!
uj5u.com熱心網友回復:
如果允許使用非標準 C 函式strptime():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Return -1 on error
time_t DR_string_to_time(const char *s) {
// Get current year
time_t t = time(NULL);
if (t == -1) {
return -1;
}
struct tm *now = localtime(&t);
if (now == NULL) {
return -1;
}
// Assume current year
struct tm DR_time = {.tm_year = now->tm_year, .tm_isdst = -1};
if (strptime(s, "%b %d %H:%M", &DR_time) == NULL) {
return -1;
}
t = mktime(&DR_time);
return t;
}
注意:"%b %d %H:%M"(month, day, hour, minute) 不包含year,因此代碼需要一些 year 來形成time_t.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362360.html
