Maxx
Maxx

Reputation: 602

C++ Boost convert UNIX Timestamp to MySQL compatible DATETIME String

I'm trying to convert a UNIX Timestamp which is in long to a Date Time string that needs to be stored in MySQL, in this format 2016-02-01 03:15:10

This is what i have so far. Its not working on the time extraction part. I couldn't find any constructor for boost::posix_time::time_duration that can take directly a boost::posix_time::ptime object. So i tried to include a workaround. But it doesn't work in the hours() part.

static inline std::string getDateTime(long timestamp) {
      std::stringstream date_str;
      boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);

      /* workaround to somehow get a time_duration object constructed */
      boost::posix_time::ptime pt_temp = boost::posix_time::from_time_t(0);

      boost::gregorian::date d = pt_1.date();

      boost::posix_time::time_duration td = pt_1 - pt_temp;

      /* construct the Date Time string */
      date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
               << td.hours() << ":" << td.minutes() << ":" << td.seconds();

      return date_str.str();
    }

With an Timestamp input such as 1455892259 i'm getting this 2016-02-19 404414:30:59 as a DateTime String from the function. How to actually get the correct Date Time string which in this case would be 2016-02-19 14:30:59. Using Boost for this is compulsory.

UPDATE

This is the final working function rewritten using the answer provided by Jarra McIntyre below.

static inline std::string getDateTime(long timestamp) {
      std::stringstream date_str;
      boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);

      boost::gregorian::date d = pt_1.date();

      auto td = pt_1.time_of_day();

      /* construct the Date Time string */
      date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
               << td.hours() << ":" << td.minutes() << ":" << td.seconds();

      return date_str.str();
    }

Upvotes: 0

Views: 1063

Answers (1)

Jarra McIntyre
Jarra McIntyre

Reputation: 1275

Use

auto td = pt_1.time_of_day();

There is no need for a workaround to get the time of day. The number of hours being displayed in your question is probably the number of hours between 1970-01-01 00:00 and 2016-02-19 14:00. For your method of getting the time_duration to work you would have to construct a ptime on the same day not at unix time 0.

Upvotes: 1

Related Questions