c++strftime

Using Strftime to format DateTime


I am working on a function to format the input timestamp to the input format.

std::string 1stformat = "dd - MM - yyyy HH 'Hours' mm 'Minutes' ss 'Seconds' SSS 'Miliseconds –' a '– Time Zone: ' Z '-' zzzz";//will not print anything
std::string 2ndformat = "'This took about' h 'minutes and' s 'seconds.'";//will print out

After format

char date_string[100];
strftime(date_string, 50, format.c_str(), curr_tm);

My problem is that there will be sometimes the input format too long which made the buffer date_string not enough to content. I am just getting into C++ for the past 3 weeks so I don't have much ex about this.


Solution

  • A wrapper for strftime() that grows a buffer as needed until it's big enough to fit the desired time string:

    #include <ctime>
    #include <iostream>
    #include <memory>
    #include <string>
    
    std::string safe_strftime(const char *fmt, const std::tm *t) {
      std::size_t len = 10; // Adjust initial length as desired. Maybe based on the length of fmt?
      auto buff = std::make_unique<char[]>(len);
      while (std::strftime(buff.get(), len, fmt, t) == 0) {
        len *= 2;
        buff = std::make_unique<char[]>(len);
      }
      return std::string{buff.get()};
    }
    
    int main() {
      std::time_t now;
      std::time(&now);
      std::cout << safe_strftime("The date is %Y-%m-%d", std::localtime(&now))
                << '\n';
      return 0;
    }