user1687451
user1687451

Reputation: 1

Attempting to convert a time_t data type to have (dd/mm/yyyy) format C++

My question is pretty much in the title. I have a function call with a parameter of type time_t, and I need to initialize a variable to today's date, month, and year, and send it via the argument. For example,

void WebCall(time_t TodaysDate)

Where TodaysDate is the populated variable with the format DD/MM/YYYY with the slashes included. Is this possible? I can't change the data type from time_t to SYSTEMTIME or anything else. This is coded in C++. Any Ideas?

Upvotes: 0

Views: 1182

Answers (2)

amdn
amdn

Reputation: 11582

time_t is "unix time" and is the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. As MSN answered you can convert that to a date using gmtime, for most common purposes, UTC is synonymous with GMT. You didn't specify in the question but if you need the local date use localtime instead of gmtime. Here's a function that'll do that for you and return a std::string:

#include <time.h>
#include <string>

std::string time_to_local_date( time_t utc )
{
    struct tm *now = localtime(&utc);
    char buffer[80];
    strftime(buffer, 80, "%d/%m/%Y", now);
    return std::string(buffer);
}

Upvotes: 1

MSN
MSN

Reputation: 54634

If you mean time_t, you can format it using gmtime and strftime:

time_t TodaysDate= ...;
struct tm * ptm= gmtime(&time);
char buffer[80];
strftime(buffer, 80, "%d/%m/%Y", ptm);

Upvotes: 1

Related Questions