Boost logo

Boost Users :

From: Jeff Garland (jeff_at_[hidden])
Date: 2004-07-22 19:21:45


On Thu, 22 Jul 2004 07:45:15 -0700, Matt Schuckmann wrote
> Has anybody ever implimented a to_time_t function/method for the
> ptime class to create a time_t from a ptime. I tried doing it
> similar to the way from_time_t does it but I'm not getting the right
> answer.
>
> It's nice that you can convert from a time_t for use with legacy
> code but sometimes you need to go back the other way.
>
> Herer is my to_time_t function that does not appear to be working
> inline
> std::time_t to_time_t(ptime t)
> {
> if( t == neg_infin )
> return 0;
> else if( t == pos_infin )
> return LONG_MAX;
> ptime start(gregorian::date(1970,1,1),time_duration(0,0,0));
> return (t-start).total_seconds();
> }

Odd. It works fine for me. Here's my slightly cleaned up version with command
line interface for testing:

#include "boost/date_time/posix_time/posix_time.hpp"
#include <string>
#include <iostream>

using namespace boost::posix_time;
using namespace boost::gregorian;

inline
std::time_t to_time_t(ptime t)
{
  if( t == neg_infin )
     return 0;
  else if( t == pos_infin )
     return LONG_MAX;
  ptime start(date(1970,1,1));
  return (t-start).total_seconds();
}

int
main()
{
  std::cout << "***** Time_t calculator *****" << std::endl;
  std::cout << "Enter a time as in yyyy-mm-dd hh:mm:ss format" << std::endl;
  std::cout << "For example: 2003-3-25 00:55:26" << std::endl;
  std::cout << "Time: ";
  std::string ts;
  std::getline(std::cin, ts);
  ptime t2 = time_from_string(ts);
  std::cout << "seconds since 1/1/1970: " << to_time_t(t2) << std::endl;
}

Couple of runs:

***** Time_t calculator *****
Enter a time as in yyyy-mm-dd hh:mm:ss format
For example: 2003-3-25 00:55:26
Time: 2003-3-25 00:56:26
seconds since 1/1/1970: 1048553786

***** Time_t calculator *****
Enter a time as in yyyy-mm-dd hh:mm:ss format
For example: 2003-3-25 00:55:26
Time: 1970-1-1 0:0:1
seconds since 1/1/1970: 1

What is your environment (compiler, boost version, etc)?

Jeff


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net