-1

I need to write files with the current date included in the name. Currently this is what I have tried:

    time_t t = time(0);
    struct tm * now = localtime(&t);
    string date=now->tm_mday+'/'+(now->tm_mon+1)+'/'+(now->tm_year+1900);

Preferably I'd like to keep this method of getting the date as I have used it earlier on in my program.

Cameron L
  • 86
  • 12

2 Answers2

5

I would use std::put_time, something like this:

time_t t = time(0);
struct tm * now = localtime(&t);

your_file << std::put_time(now, "%d/%m/%Y");

If you mean that you need to include the date in the name of a new file, then write to a stringstream, and use your_stream.str() to get a string containing the value.

If (though it strikes me as unlikely) you find that imposes excessive overhead, you could use strftime instead. It writes a date/time directly to a C-style string:

char buffer[64];

strftime(buffer, sizeof(buffer), "%d/%m/%Y", now);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Sorry, I realise i wasn't very clear. What I'm actually trying to do is write the file name with the date in it. For this I need to be able to have it as a String. – Cameron L May 02 '16 at 16:18
2

I have often used std::strftime a bit like this:

// use strftime to format time_t into a "date time"
std::string get_date(std::time_t timer)
{
    char buf[sizeof("02/05/2015")]; // big enough for 02/05/2015\0
    std::tm tp = *std::localtime(&timer); // not thread safe
    return {buf, std::strftime(buf, sizeof(buf), "%d/%m/%Y", &tp)};
}

int main()
{
    std::cout << get_date(std::time(0)) << '\n';
}

Output:

02/05/2016
Galik
  • 47,303
  • 4
  • 80
  • 117