Boost logo

Boost Users :

From: Jeff Garland (jeff_at_[hidden])
Date: 2007-12-24 09:04:25


tonyaim83 wrote:
> Hi
> I'm using Date time library for the first time so no idea how best make use
> of it.
> My primary target is to check if the first timestamp and second timestamp
> entered by the user are in a span of one hour.
> Format of input string is as follows YYYYDDMM-HH:MM:SS(20071015-17:47:10)
> Now if the second string is also in the an hour span it should return true
> otherwise false.
> I m thinking of doing this like
> std::string to_iso_string(date d1)
> ptime p1(d1, time_duration("17:21:23"));
> std::string to_iso_string(date d2)
> ptime p2(d2, time_duration("17:22:23"));
>
> ptime p3=p2-p1;
> if (p3>1)
> {
> return false;
> }
> I could also find a function which has a separator T
> std::string to_iso_extended_string(ptime);
> How can i make use of this function as in my case the separtor of date- time
> is "-" Or a better way to perform the same task.
>

I suggest you use the facet i/o. The program below prints "less than one
hour". The time_input_facet defines the parsing format:

     time_input_facet* timefacet = new time_input_facet("%Y%m%d-%H:%M:%S");

Rest of the program should be pretty obvious.

*****************************
#include "boost/date_time.hpp"
#include <iostream>

using namespace boost::posix_time;

ptime
parse_time(const std::string& s)
{

   ptime t; //not-a-date-time
   try {
     std::stringstream ss(s.c_str());
     time_input_facet* timefacet = new time_input_facet("%Y%m%d-%H:%M:%S");
     ss.imbue(std::locale(std::locale::classic(), timefacet));
     ss.exceptions(std::ios_base::failbit); // turn on exceptions
     ss >> t;
   }
   catch(std::exception& e) {
     std::cout << "Incorrect date format entered" << std::endl;
     std::cout << e.what() << std::endl;
   }
   return t;

}

int main()
{

   hours one_hour(1);
   ptime t1 = parse_time("20071015-17:47:10");
   ptime t2 = parse_time("20071015-17:47:45");
   if (!(t1.is_not_a_date_time() || t2.is_not_a_date_time())) {
     if (t2-t1 < one_hour) {
       std::cout << "less than one hour" << std::endl;
     }
   }

}


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