C++ ctime() 迄今为止格式化的字符串?



我正在尝试更改我的 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 字符数组或字符串数组获取 month 作为字符串。

另请参阅:https://zetcode.com/articles/cdatetime/

最新更新