开发者

basic boost date_time input format question

开发者 https://www.devze.com 2022-12-26 14:39 出处:网络
I\'ve got a pointer to a string, (char *) as input. The date/time looks like this: Sat, 10 Apr 2010 19:30:00

I've got a pointer to a string, (char *) as input. The date/time looks like this:

Sat, 10 Apr 2010 19:30:00

I开发者_如何学JAVA'm only interested in the date, not the time. I created an "input_facet" with the format I want:

boost::date_time::date_input_facet inFmt("%a %d %b %Y");

but I'm not sure what to do with it. Ultimately I'd like to create a date object from the string. I'm pretty sure I'm on the right track with that input facet and format, but I have no idea how to use it.

Thanks.


You can't always dismiss the time part of a string due to time zone differences a date can change.

  • to parse date/time you could use time_input_facet<>
  • to extract a date part from it you could use .date() method

Example:

// $ g++ *.cc -lboost_date_time && ./a.out 
#include <iostream>
#include <locale>
#include <sstream>

#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
 
int main() {
  using namespace std;
  using boost::local_time::local_time_input_facet;
  using boost::posix_time::ptime;

  stringstream ss;
  ss <<                                     "Sat, 10 Apr 2010 19:30:00";
  ss.imbue(locale(locale::classic(),       
                  new local_time_input_facet("%a, %d %b %Y " "%H:%M:%S")));
  ptime t;
  ss.exceptions(ios::failbit);
  ss >> t;
  cout << "date: " << t.date() << '\n' ;
}

Run it:

$ g++ *.cc -lboost_date_time && ./a.out 
date: 2010-Apr-10
0

精彩评论

暂无评论...
验证码 换一张
取 消