我正在尝试更改Unix时间戳的格式。但是我看不到任何自定义格式的选项。
这是我的代码:
tempstring = "Your last login was: ";
time_t lastLogin = player->getLastLoginSaved(); // &lastLogin = Unix timestamp
tempstring += ctime(&lastLogin);
tempstring.erase(tempstring.length() -1);
tempstring += ".";
AddTextMessage(msg, MSG_STATUS_DEFAULT, tempstring.c_str());
这将给我输出:
Your last login was: Sun Sep 29 02:41:40 2019.
如何将其更改为这种格式?
Your last login was: 29. Sep 2019 02:41:40 CET.
我相信格式为:%d. %b %Y %H:%M:%S CET
但是我该如何使用ctime()?请让我知道是否有任何更改格式的方法。我是C ++的新手,所以如果我需要其他库,请告诉我。
您可以使用time.h。将time_t
分解为struct tm
。
struct tm *localtime(const time_t *clock);
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month 0 to 11*/
int tm_year; /* years since 1900*/
int tm_wday; /* day of the week 0 to 6*/
int tm_yday; /* day in the year 0 to 365*/
int tm_isdst; /* daylight saving time */
};
然后使用sprintf
格式,记住要添加偏移量。例如。 snprintf(cTimeStr, sizeof(cTimeStr), "%04d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
使用const char数组或字符串数组获取月份作为字符串。