rick astley
rick astley

Reputation: 109

C++ ctime() to date formatted string?

I am trying to change format of my unix timestamp. But I don't see any option to customize the format.

This is my code:

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());

This will give me an output of:

Your last login was: Sun Sep 29 02:41:40 2019.

How can I change this to a format like this instead?

Your last login was: 29. Sep 2019 02:41:40 CET.

I believe the format would be: %d. %b %Y %H:%M:%S CET

But how can I do that with ctime()? Please let me know if there is any way to change format. I am new with C++ so if I need another library please let me know.

Upvotes: 1

Views: 1755

Answers (1)

LegendofPedro
LegendofPedro

Reputation: 1401

You can use time.h. Breakdown your time_t into a 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 */
};

Then format with sprintf, remembering to add offsets. E.g. 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);

Use const char arrays or string array to get month as a string.

See also: https://zetcode.com/articles/cdatetime/

Upvotes: 1

Related Questions