C ++ ctime()是日期格式化的字符串吗?

问题描述 投票:0回答:1

我正在尝试更改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 ++的新手,所以如果我需要其他库,请告诉我。

c++ date datetime formatting unix-timestamp
1个回答
0
投票

您可以使用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数组或字符串数​​组获取月份作为字符串。

另请参见:http://zetcode.com/articles/cdatetime/

© www.soinside.com 2019 - 2024. All rights reserved.