Ron Gross
Ron Gross

Reputation: 1624

Get year from boost date as string

I am using boost's date object I want to get the year from this object as string or as int

I didn't find the simple way to do this Thank you! Ron

Upvotes: 0

Views: 1742

Answers (3)

Ahmed Junaid Khalid
Ahmed Junaid Khalid

Reputation: 1

A good option is to use the inbuilt function in the boost library.

#include <iostream>
#include <string>
#include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o

using namespace boost::gregorian;
using namespace std;

date d(2000, Jan, 1);
string a = to_simple_string(d);

Upvotes: 0

Delta_Fore
Delta_Fore

Reputation: 3271

I wrote these functions for a project of mine which you might find useful. I did it this way after I found the lexical_cast was causing a performance problem in my specific code. (No warranties, though it's run fine in our prod environment for a few years;)

using namespace boost;
    gregorian::date date_from_str(const char* dateStr,const char* format) {
        int year;
        int month;
        int day;
        sscanf_s(dateStr,format,&year,&month,&day);
        return gregorian::date(year,month,day);
    }
    std::string date_to_str(const gregorian::date& date,const char* format) {
        char buf[10];
        gregorian::date::ymd_type ymd = date.year_month_day();
        sprintf_s(buf,sizeof(buf),format,ymd.year,ymd.month,ymd.day);
        return std::string(buf);
    }

    gregorian::date dateInt_to_date(int dateInt) {
        const int day = dateInt % 100;
        const int month = (dateInt / 100) % 100;
        const int year = dateInt / 10000;
        return gregorian::date(year,month,day);
    }

You can edit this to just return the year part

Upvotes: 0

nothrow
nothrow

Reputation: 16168

#include <boost/date_time/local_time/local_time.hpp>
#include <boost/lexical_cast.hpp>
#include <string>


std::string x = boost::lexical_cast<std::string>
                    (second_clock::local_time().date().year());

should do.

Upvotes: 5

Related Questions