Boost.Date_Time

Introduction
A set of date-time libraries based on generic programming concepts.

Conceptual

Motivation
The motivation for this library comes from working with and helping build several date-time libraries on several projects. Date-time libraries provide fundamental infrastructure for most development projects. However, most of them have limitations in their ability to calculate, format, convert, or perform some other functionality. For example, most libraries do not correctly handle leap seconds, provide concepts such as infinity, or provide the ability to use high resolution or network time sources. These libraries also tend to be rigid in their representation of dates and times. Thus customized policies for a project or subproject are not possible.
Programming with dates and times should be almost as simple and natural as programming with strings and integers. Applications with lots of temporal logic can be radically simplified by having a robust set of operators and calculation capabilities. Classes should provide the ability to compare dates and times, add lengths or time durations, retrieve dates and times from clocks, and work naturally with date and time intervals.
Another motivation for development of the library was to apply modern C++ library design techniques to the date-time domain. Really to build a framework for the construction of building temporal types. For example, by providing iterators and traits classes to control fundamental properties of the library. To the authors knowledge this library is the only substantial attempt to apply modern C++ to a date-time library.

Domain Concepts
The date time domain is rich in terminology and problems. The following is a brief introduction to the concepts you will find reflected in the library.
The library supports 3 basic temporal types:
Time Point -- Specifier for a location in the time continuum.
Time Duration -- A length of time unattached to any point on the time continuum.
Time Interval -- A duration of time attached to a specific point in the time continuum. Also known as a time period.
Each of these temporal types has a Resolution which is defined by the smallest representable duration. A Time system provides all these categories of temporal types as well as the rules for labeling and calculating with time points. Calendar Systems are simply time systems with a maximum resolution of one day. The Gregorian system is the most widely used calendar system today (the ISO system is basically a derivative of this). However, there are many other calendar systems as well. UTC (Coordinated Universal Time) is a widely used civil time system. UTC is adjusted for earth rotation at longitude 0 by the use of leap seconds (This is not predictable, only as necessary). Most local time systems are based on UTC but are also adjusted for earth rotation so that daylight hours are similar everywhere. In addition, some local times include daylight savings time (DST) adjustments to shift the daylight hours during the summer.
A Clock Device is software component (tied to some hardware) that provides the current date or time with respect to a time system. A clock can measure the current time to a known resolution which may be higher or lower than a particular time representation.
The library provides support for calculating with dates and times. However, time calculations are not quite the same as calculating with integers. If you are serious about the accuracy of your time calculations need to read about Stability, Predictability, and Approximations.
Basic Terminology
Calculations
Stability, Predictability, and Approximations
References

Design Concepts
A large part of the genesis of this library has been the observation that few date-time libraries are built in a fashion that allows customization and extension. A typical example, the calendar logic is built directly into the date class. Or the clock retrieval functions are built directly into the time class. These design decisions usually make it impossible to extend or change the library behavior. At a more fundamental level, there are usually assumptions about the resolution of time representation or the gregorian calendar.
Often times, the result is that a project must settle for a less than complete library because of a requirement for high resolution time representation or other assumptions that do not match the implementation of the library. This is extremely unfortunate because development of a library of this sort is far from a trivial task.
While the design is far from perfect the current design is far more flexible than any date-time library the author is aware of. It is expected that the various aspects of extensibility will be better documented in future versions. Information about the design goals of the library is summarized here.

More Information
The design of the library is currently being evolved using Wiki and email discussions. You can find more information at:
Boost Wiki GDTL Start Page
Full Doxygen Reference Manual

Gregorian

Gregorian Date System
Introduction -- Usage Examples

Introduction
The gregorian date system provides a date programming system based the Gregorian Calendar. The first introduction of the Gregorian calendar was in 1582 to fix an error in the Julian Calendar. However, many local jurisdictions did not adopt this change until much later. Thus there is potential confusion with historical dates.
The implemented calendar is a "propleptic Gregorian calendar" which extends dates back prior to the Gregorian Calendar's first adoption in 1582. The current implementation supports dates in the range 1400-Jan-01 to 10000-Jan-01. Many references will represent dates prior to 1582 using the Julian Calendar, so caution is in order if accurate calculations are required on historic dates. See Calendrical Calculations by Reingold & Dershowitz for more details. Date information from Calendrical Calculations has been used to cross-test the correctness of the Gregorian calendar implementation.
All types for the gregorian system are found in namespace boost::gregorian. The library supports a convenience header boost/date_time/gregorian/gregorian_types.hpp that will include all the classes of the library with no input/output dependency. Another header boost/date_time/gregorian/gregorian.hpp will include the types and the input/output code.
The class boost::gregorian::date is the primary temporal type for users. If you are interested in learning about writing programs do specialized date calculations such as finding the "first sunday in april" see the date generators and algorithms page.

Usage Examples
Example	Description
Days AliveDays Till New Year	Simple date arithmetic. Retrieve current day from clock.
Dates as strings	Simple parsing and formatting of dates from/to strings
Date Period Calculations	See if a date is in a set of date periods (eg: is it a holiday/weekend)
Print a month	Small utility program which prints out all the days in a month from command line. Need to know if 1999-Jan-1 was a Friday or a Saturday? This program shows how to do it.
Print Holidays	Uses date generators to convert abstract specification into concrete set of dates.

Date Class
Introduction -- Header -- Construction -- Construct from String -- Construct from Clock -- Accessors -- Convert to String -- Operators

Introduction
The class boost::gregorian::date is the primary interface for date programming. In general, the date class is immutable once constructed although it does allow assignment.
Other techniques for creating dates include date iterators and date algorithms or generators.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
date(greg_year year, greg_month month, greg_day day)	Construct from parts of date. Throws bad_year, bad_day_of_month, or bad_day_month (derivatives of std::out_of_range) if the year, month or day are out of range.	date d(2002,Jan,10)
date(date d)	Copy constructor	date d1(d)
date(special_values sv)	Constructor for infinities, not-a-date-time, max_date_time, and min_date_time	date d1(neg_infin); date d2(pos_infin); date d3(not_a_date_time); date d4(max_date_time); date d5(min_date_time);
date;	Default constructor. Creates a date object initialized to not_a_date_time. NOTE: this constructor can be disabled by defining DATE_TIME_NO_DEFAULT_CONSTRUCTOR (see compiler_config.hpp)	date d; // d => not_a_date_time

Construct from String
Syntax	Description	Example
date from_string(const std::string&)	From delimited date string where with order year-month-day eg: 2002-1-25	std::string ds("2002/1/25"); date d(from_string(ds))
date from_undelimited_string(const std::string&)	From iso type date string where with order year-month-day eg: 20020125	std::string ds("20020125"); date d(from_undelimited_string(ds))

Construct from Clock
Syntax	Description	Example
day_clock::local_day()	Get the local day based on the time zone settings of the computer.	date d(day_clock::local_day())
day_clock::universal_day()	Get the UTC day.	date d(day_clock::universal_day())

Accessors
Syntax	Description	Example
greg_year year() const	Get the year part of the date.	date d(2002,Jan,10); d.year() --> 2002;
greg_month month() const	Get the month part of the date.	date d(2002,Jan,10); d.month() --> 1;
greg_day day() const	Get the day part of the date.	date d(2002,Jan,10); d.day() --> 10;
greg_ymd year_month_day() const	Return a year_month_day struct. More efficient when all 3 parts of the date are needed.	date d(2002,Jan,10); date::ymd_type ymd = d.year_month_day(); ymd.year --> 2002, ymd.month --> 1, ymd.day --> 10
greg_day_of_week day_of_week() const	Get the day of the week (eg: Sunday, Monday, etc.	date d(2002,Jan,10); d.day() --> Thursday;
bool is_infinity() const	Returns true if date is either positive or negative infinity	date d(pos_infin); d.is_infinity() --> true;
bool is_neg_infinity() const	Returns true if date is negative infinity	date d(neg_infin); d.is_neg_infinity() --> true;
bool is_pos_infinity() const	Returns true if date is positive infinity	date d(neg_infin); d.is_pos_infinity() --> true;
bool is_not_a_date() const	Returns true if value is not a date	date d(not_a_date_time); d.is_not_a_date() --> true;
long modjulian_day() const	Returns the modified julian day for the date.
long julian_day() const	Returns the julian day for the date.
int week_number() const	Returns the ISO 8601 week number for the date.

Convert to String
Syntax	Description	Example
std::string to_simple_string(date d)	To YYYY-mmm-DD string where mmm 3 char month name.	2002-Jan-01
std::string to_iso_string(date d)	To YYYYMMDD where all components are integers.	20020131
std::string to_iso_extended_string(date d)	To YYYY-MM-DD where all components are integers.	2002-01-31

Operators
Syntax	Description	Example
operator<<	Stream output operator	date d(2002,Jan,1) std::cout << d << std::endl;
operator==, operator!=, operator>, operator< operator>=, operator<=	A full complement of comparison operators	d1 == d2, etc
date operator+(date_duration) const	Return a date adding a day offset	date d(2002,Jan,1); date_duration dd(1); date d2 = d + dd;
date operator-(date_duration) const	Return a date by adding a day offset	date d(2002,Jan,1); date_duration dd(1); date d2 = d - dd;
date_duration operator-(date) const	Return a date duration by subtracting two dates	date d1(2002,Jan,1); date d2(2002,Jan,2); date_duration dd = d2-d1;
top

Date Duration (aka Days)
Introduction -- Header -- Construction -- Operators

Introduction
As of version 1_32 the date_duration class has been typdefed as days in the boost::gregorian namespace. Throughout the examples you will find days used instead of date_duration.
The class boost::gregorian::date_duration is a simple day count used for arithmetic with gregorian::date. A duration can be either positive or negative.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
date_duration(long)	Create a duration count.	date_duration dd(3); //3 days

Accessors
Syntax	Description	Example
long days() const	Get the day count.	date_duration dd(3); dd.days() --> 3
bool is_negative() const	True if number of days is less than zero.	date_duration dd(-1); dd.is_negative() --> true
static date_duration unit()	Return smallest possible unit of duration type.	date_duration::unit() --> date_duration(1)

Operators
Syntax	Description	Example
operator==, operator!=, operator>, operator< operator>=, operator<=	A full complement of comparison operators	dd1 == dd2, etc
date_duration operator+(date_duration) const	Add date durations.	date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 + dd2;
date_duration operator-(date_duration) const	Subtract durations.	date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 - dd2;
top

Date Period
Introduction -- Header -- Construction -- Accessors -- Convert to String -- Operators

Introduction
The class boost::gregorian::date_period provides direct representation for ranges between two dates. Periods provide the ability to simplify some types of calculations by simplifying the conditional logic of the program. For example, testing if a date is within an irregular schedule such as a weekend or holiday can be accomplished using collections of date periods. This is facilitated by several methods that allow evaluation if a date_period intersects with another date period, and to generate the period resulting from the intersection. The period calculation example provides an example of this.
Date periods used in combination with infinity values have the ability to represent complex concepts such as 'until further notice'.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
date_period(date begin, date end)	Create a period as [begin, end). If last is <= begin then the period will be defined as null.	date_period dp(date(2002,Jan,10), date(2002,Jan,12));
date_period(date start, date_duration len)	Create a period as [begin, begin+len). If len is <= zero then the period will be defined as null.	date_period dp(date(2002,Jan,10), date_duration(2));
date_period(date_period rhs)	Copy constructor	date_period dp1(dp)

Accessors
Syntax	Description	Example
date begin() const	Return first day of period.	date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.begin() --> 2002-Jan-01
date last() const	Return last date in the period	date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.last() --> 2002-Jan-09
date end() const	Return one past the last in period	date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.end() --> 2002-Jan-10
date_duration length() const	Return the length of the date_period	date_period dp(date(2002,Jan,1), date_duration(2)); dp.length() --> 2
bool is_null() const	True if period is not well formed. eg: start less than end	date_period dp(date(2002,Jan,10), date(2002,Jan,1)); dp.begin() --> true
bool contains(date) const	True if date is within the period	date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.contains(date(2002,Jan,2)) --> true
bool contains(date_period) const	True if date period is within the period	date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp1.contains(dp2) --> true dp2.contains(dp1) --> false
bool intersects(date_period) const	True if periods overlap	date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp2.intersects(dp1) --> true
date_period intersection(date_period) const	Calculate the intersection of 2 periods. Null if no intersection.	date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp2.intersection(dp1) --> dp2
date_period is_adjacent(date_period) const	Check if two periods are adjacent, but not overlapping.	date_period dp1(date(2002,Jan,1), date(2002,Jan,3)); date_period dp2(date(2002,Jan,3), date(2002,Jan,10)); dp2.is_adjacent(dp1) --> true
date_period is_after(date) const	Determine the period is after a given date.	date_period dp1(date(2002,Jan,10), date(2002,Jan,30)); date d(2002,Jan,3); dp1.is_after(d) --> true
date_period is_before(date) const	Determine the period is before a given date.	date_period dp1(date(2002,Jan,1), date(2002,Jan,3)); date d(2002,Jan,10); dp1.is_before(d) --> true
date_period merge(date_period) const	Returns union of two periods. Null if no intersection.	date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,9), date(2002,Jan,31)); dp2.merge(dp1) --> 2002-Jan-01/2002-Jan-31
date_period span(date_period) const	Combines two periods and any gap between them such that start = min(p1.start, p2.start) and end = max(p1.end , p2.end)	date_period dp1(date(2002,Jan,1), date(2002,Jan,5)); date_period dp2(date(2002,Jan,9), date(2002,Jan,31)); dp2.hull(dp1) --> 2002-Jan-01/2002-Jan-31
date_period shift(date_duration)	Add duration to both start and end.	date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); dp1.shift(date_duration(1)); --> 2002-Jan-02/2002-Jan-11

Convert to String
Syntax	Description	Example
std::string to_simple_string(date_period dp)	To [YYYY-mmm-DD/YYYY-mmm-DD] string where mmm is 3 char month name.	[2002-Jan-01/2002-Jan-31]

Operators
Syntax	Description	Example
operator<<	ostream operator for date_period. Uses facet to format time points. Typical output: [2002-Jan-01/2002-Jan-31].	std::cout << dp << std::endl;
operator==, operator!=, operator>, operator<	A full complement of comparison operators	dp1 == dp2, etc
operator<	True if dp1.end() less than dp2.begin()	dp1 < dp2, etc
operator>	True if dp1.begin() greater than dp2.end()	dp1 > dp2, etc
top

Date Iterators
Introduction -- Header -- Overview

Introduction
Date iterators provide a standard mechanism for iteration through dates. Date iterators are a model of Input Iterator and can be used to populate collections with dates and other date generation tasks. For example, the print month example iterates through all the days in a month and prints them.
All of the iterators here derive from boost::gregorian::date_iterator.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Overview
Class	Construction Parameters	Description
date_iterator		Common base class for all day level iterators.
day_iterator	date start_date, int day_count=1	Iterate day_count days at a time.
week_iterator	date start_date, int week_offset=1	Iterate week_offset weeks at a time.
month_iterator	date start_date, int month_offset=1	Iterate month_offset months. There are special rules for handling the end of the month. These are: if start date is last day of the month, always adjust to last day of the month. If date is beyond the end of the month (eg: jan 31 + 1 month) adjust back to end of month.
year_iterator	date start_date, int year_offset=1	Iterate year_offset years. The year_iterator will always land on the day of the date parameter except when date is Feb 28 in a non-leap year. In this case the iterator will return Feb 29 for leap years (eg: 2003-Feb-28, 2004-Feb-29, 2005-Feb-28).
top

Date Generators/Algorithms

Date Generators/Algorithms
Introduction -- Header -- Class Overview -- Function Overview

Introduction
Date algorithms or generators are tools for generating other dates or schedules of dates. A generator function starts with some part of a date such as a month and day and is supplied another part to then generate a concrete date. This allows the programmer to represent concepts such as "The first Sunday in February" and then create a concrete set of dates when provided with one or more years. Note: As of boost version 1_31_0, date generator names have been changed. Old names are still available but are no longer documented and may someday be deprecated
Also provided are stand-alone functions for generating a date, or calculation a duration of days. These functions take a date object and a weekday object as parameters.
All date generator classes and functions are in the boost::gregorian namespace.
The print holidays example shows a detailed usage example.

Header
#include "boost/date_time/date_generators.hpp"

Overview
Class	Construction Parameters	get_date Parameter	Description	Example
year_based_generator	abstract base class	greg_year year	A unifying date_generator base type for: partial_date, nth_day_of_the_week_in_month, first_day_of_the_week_in_month, and last_day_of_the_week_in_month	The print holidays example shows a detailed usage example.
last_day_of_the_week_in_month	greg_weekday or weekday, greg_month or month	greg_year or year	Calculate something like last Monday of January	last_day_of_the_week_in_month lwdm(Monday,Jan); date d = lwdm.get_date(2002);//2002-Jan-28
first_day_of_the_week_in_month	greg_weekday or weekday, greg_month or month	greg_year or year	Calculate something like first Monday of January	first_day_of_the_week_in_month fdm(Monday,Jan); date d = fdm.get_date(2002);//2002-Jan-07
partial_date	greg_day, greg_month or month	greg_year	Generates a date by applying the year to the given month and day.	partial_date pd(1,Jan); date d = pd.get_date(2002);//2002-Jan-01
first_day_of_the_week_after	greg_weekday or weekday	date	Calculate something like First Sunday after Jan 1,2002	first_day_of_the_week_after fdaf(Monday); date d = fdaf.get_date(date(2002,Jan,1));//2002-Jan-07
first_day_of_the_week_before	greg_weekday or weekday	date	Calculate something like First Monday before Feb 1,2002	first_day_of_the_week_before fdbf(Monday); date d = fdbf.get_date(date(2002,Feb,1));//2002-Jan-28

Function Overview
Function Prototype	Description	Example
days days_until_weekday (const date&, const greg_weekday&)	Calculates the number of days from given date until given weekday.	date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); days_until_weekday(d, gw); // 3 days
days days_before_weekday (const date&, const greg_weekday&)	Calculates the number of day from given date to previous given weekday.	date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); days_before_weekday(d, gw); // 4 days
date next_weekday (const date&, const greg_weekday&)	Generates a date object representing the date of the following weekday from the given date.	date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); next_weekday(d, gw); // 2004-Jun-4
date previous_weekday (const date&, const greg_weekday&)	Generates a date object representing the date of the previous weekday from the given date.	date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); previous_weekday(d, gw); // 2004-May-28
top

Gregorian Calendar
Introduction -- Header -- Functions

Introduction
The class boost::gregorian::gregorian_calendar implements the functions necessary to create the gregorian date system. It converts to the year-month-day form of a date to a day number representation and back.
For most purposes this class is simply accessed by gregorian::date and is not used directly by the user. However, there are useful functions that might be of use such as the end_of_month_day function.
The print month example demonstrates this.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Functions
Syntax	Description	Example
static short day_of_week(ymd_type)	Return the day of the week (0==Sunday, 1==Monday, etc)	See also gregorian::date day_of_week
static date_int_type day_number(ymd_type)	Convert a ymd_type into a day number. The day number is an absolute number of days since the epoch start.
static short end_of_month_day(year_type, month_type)	Given a year and month determine the last day of the month.
static ymd_type from_day_number(date_int_type)	Convert a day number to a ymd struct.
static bool is_leap_year(year_type)	Returns true if specified year is a leap year.	gregorian_calendar::is_leap_year(2000) --> true
top

Class day_clock
Class day_clock
top

Posix Time

Posix Time System
Introduction -- Usage Examples

Introduction
Defines a non-adjusted time system with nano-second/micro-second resolution and stable calculation properties. The nano-second resolution option uses 96 bits of underlying storage for each ptime while the micro-second resolution uses 64 bits per ptime (see Build Options for details). This time system uses the Gregorian calendar to implement the date portion of the time representation.

Usage Examples
Example	Description
Time Math	A few simple calculations using ptime and time_durations.
Print Hours	Retrieve time from clock, use a time_iterator.
Local to UTC Conversion	Demonstrates a couple different ways to convert a local to UTC time including daylight savings rules.
Time Periods	Some simple examples of intersection and display of time periods.

Ptime Class
Introduction -- Header -- Construction -- Construct from String -- Construct from Clock -- Construct using Conversion functions -- Accessors -- Conversion To String -- Operators

Introduction
The class boost::posix_time::ptime is the primary interface for time point manipulation. In general, the ptime class is immutable once constructed although it does allow assignment.
Class ptime is dependent on gregorian::date for the interface to the date portion of a time point.
Other techniques for creating times include time iterators.

Header

      #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o
      or
      #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
ptime(date,time_duration)	Construct from a date and offset	ptime t1(date(2002,Jan,10), time_duration(1,2,3)); ptime t2(date(2002,Jan,10), hours(1)+nanosec(5));
ptime(ptime)	Copy constructor	ptime t3(t1)
ptime(special_values sv)	Constructor for infinities, not-a-date-time, max_date_time, and min_date_time	ptime d1(neg_infin); ptime d2(pos_infin); ptime d3(not_a_date_time); ptime d4(max_date_time); ptime d5(min_date_time);
ptime;	Default constructor. Creates a ptime object initialized to not_a_date_time. NOTE: this constructor can be disabled by defining DATE_TIME_NO_DEFAULT_CONSTRUCTOR (see compiler_config.hpp)	ptime p; // p => not_a_date_time

Construct from String
Syntax	Description	Example
ptime time_from_string(const std::string&)	From delimited string.	std::string ts("2002-01-20 23:59:59.000"); ptime t(time_from_string(ts))
ptime from_iso_string(const std::string&)	From non delimited iso form string.	std::string ts("20020131T235959"); ptime t(from_iso_string(ts))

Construct from Clock
Syntax	Description	Example
static ptime second_clock::local_time();	Get the local time, second level resolution, based on the time zone settings of the computer.	ptime t(second_clock::local_time())
static ptime second_clock::universal_time()	Get the UTC time.	ptime t(second_clock::universal_day())
static ptime microsec_clock::local_time()	Get the local time using a subsecond resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the acheived resolution.	ptime t(microsec_clock::local_time())

Construct using Conversion Functions
Syntax	Description	Example
ptime from_time_t(time_t t);	Converts a time_t into a ptime.	ptime t = from_time_t(tt);
ptime from_ftime<ptime>(FILETIME ft);	Creates a ptime object from a FILETIME structure.	ptime t = from_ftime<ptime>(ft);

Accessors
Syntax	Description	Example
date date() const	Get the date part of a time.	date d(2002,Jan,10); ptime t(d, hour(1)); t.date() --> 2002-Jan-10;
time_duration time_of_day() const	Get the time offset in the day.	date d(2002,Jan,10); ptime t(d, hour(1)); t.time_of_day() --> 01:00:00;

Conversion to String
Syntax	Description	Example
std::string to_simple_string(ptime)	To YYYY-mmm-DD HH:MM:SS.fffffffff string where mmm 3 char month name. Fractional seconds only included if non-zero.	2002-Jan-01 10:00:01.123456789
std::string to_iso_string(ptime)	Convert to form YYYYMMDDTHHMMSS,fffffffff where T is the date-time separator	20020131T100001,123456789
std::string to_iso_extended_string(ptime)	Convert to form YYYY-MM-DDTHH:MM:SS,fffffffff where T is the date-time separator	2002-01-31T10:00:01,123456789

Operators
Syntax	Description	Example
operator==, operator!=, operator>, operator< operator>=, operator<=	A full complement of comparison operators	t1 == t2, etc
ptime operator+(date_duration) const	Return a ptime adding a day offset	date d(2002,Jan,1); ptime t(d,minutes(5)); date_duration dd(1); ptime t2 = t + dd;
ptime operator-(date_duration) const	Return a ptime subtracting a day offset	date d(2002,Jan,1); ptime t(d,minutes(5)); date_duration dd(1); ptime t2 = t - dd;
ptime operator+(time_duration) const	Return a ptime adding a time duration	date d(2002,Jan,1); ptime t(d,minutes(5)); ptime t2 = t + hours(1) + minutes(2);
ptime operator-(time_duration) const	Return a ptime subtracting a time duration	date d(2002,Jan,1); ptime t(d,minutes(5)); ptime t2 = t - minutes(2);
time_duration operator-(ptime) const	Take the difference between two times.	date d(2002,Jan,1); ptime t1(d,minutes(5)); ptime t2(d,seconds(5)); time_duration t3 = t2 - t1;//negative result
top

Time Duration
Introduction -- Header -- Construction -- Count Based Construction -- Construct from String -- Accessors -- Conversion To String -- Operators

Introduction
The class boost::posix_time::time_duration the base type responsible for representing a length of time. A duration can be either positive or negative. The general time_duration class provides a constructor that takes a count of the number of hours, minutes, seconds, and fractional seconds count as shown in the code fragment below. The resolution of the time_duration is configureable at compile time. See Build-Compiler Information for more information.

      using namespace boost::posix_time;
      time_duration td(1,2,3,4); //01:02:03.000000004 when resolution is nano seconds
      time_duration td(1,2,3,4); //01:02:03.000004 when resolution is micro seconds

Several small helper classes that derive from a base time_duration, as shown below, to adjust for different resolutions. These classes can shorten code and make the intent clearer.
As an example:

  
      using namespace boost::posix_time;
      
      time_duration td = hours(1) + seconds(10); //01:00:01
      td = hours(1) + nanosec(5); //01:00:00.000000005

Note that the existence of the higher resolution classes (eg: nanosec) depends on the installation of the library. See Build-Compiler Information for more information.

Header

      #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o
      or
      #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
time_duration(hours,minutes,seconds,fractional_seconds)	Construct ad duration from the counts	time_duration td(1,2,3,9); //1 hr 2 min 3 sec 9 nanoseconds

Count Based Construction
Syntax	Description	Example
hours(long)	Number of hours	time_duration td = hours(3);
minutes(long)	Number of minutes	time_duration td = minutes(3);
seconds(long)	Number of seconds	time_duration td = seconds(3);
millisec(long)	Number of milliseconds.	time_duration td = millisec(3);
microsec(long)	Number of microseconds.	time_duration td = microsec(3);
nanosec(long)	Number of nanoseconds.	time_duration td = nanosec(3);

Construct from String
Syntax	Description	Example
time_duration duration_from_string(const std::string&)	From delimited string.	std::string ts("23:59:59.000"); time_duration td(duration_from_string(ts))

Accessors
Syntax	Description	Example
long hours() const	Get the number of normalized hours.	time_duration td(1,2,3); td.hours() --> 1
long minutes() const	Get the number of minutes normalized (0..59).	time_duration td(1,2,3); td.minutes() --> 2
long seconds() const	Get the normalized number of second (0..59).	time_duration td(1,2,3); td.seconds() --> 3
long total_seconds() const	Get the total number of seconds truncating any fractional seconds.	time_duration td(1,2,3,10); td.total_seconds() --> (1*3600) + (2*60) + 3 == 3723
long fractional_seconds() const	Get the number of fractional seconds.	time_duration td(1,2,3, 1000); td.fractional_seconds() --> 1000
bool is_negative() const	True if duration is negative.	time_duration td(-1,0,0); td.is_negative() --> true
time_duration invert_sign() const	Generate a new duration with the sign inverted/	time_duration td(-1,0,0); td.invert_sign() --> 01:00:00
static boost::date_time::time_resolutions resolution()	Describes the resolution capability of the time_duration class. time_resolutions is an enum of resolution possibilities ranging from seconds to nanoseconds.	time_duration::resolution() --> nano
static time_duration::num_fractional_digits()	Returns an unsigned short holding the number of fractional digits the time resolution has.	time_duration::num_fractional_digits(); // 9 for nano, 6 for micro, etc.
boost::int64_t ticks()	Return the raw count of the duration type.	time_duration td(0,0,0, 1000); td.ticks() --> 1000
static time_duration unit()	Return smallest possible unit of duration type (1 nanosecond).	time_duration::unit() --> time_duration(0,0,0,1)

Conversion To String
Syntax	Description	Example
std::string to_simple_string(time_duration)	To HH:MM:SS.fffffffff were fff is fractional seconds that are only included if non-zero.	10:00:01.123456789
std::string to_iso_string(time_duration)	Convert to form HHMMSS,fffffffff.	100001,123456789

Operators
Syntax	Description	Example
operator==, operator!=, operator>, operator< operator>=, operator<=	A full complement of comparison operators	dd1 == dd2, etc
time_duration operator+(time_duration) const	Add durations.	time_duration td1(hours(1)+minutes(2)); time_duration td2(seconds(10)); time_duration td3 = td1 + td2;
time_duration operator-(time_duration) const	Subtract durations.	time_duration td1(hours(1)+nanosec(2)); time_duration td2 = td1 - minutes(1);
time_duration operator/(int) const	Divide the length of a duration by an integer value. Discards any remainder.	hours(3)/2 == time_duration(1,30,0); nanosec(3)/2 == nanosec(1)
time_duration operator*(int) const	Multiply the length of a duration by an integer value.	hours(3)*2 == hours(6);
top

Time Period
Introduction -- Header -- Construction -- Accessors -- Conversion To String -- Operators

Introduction
The class boost::posix_time::time_period provides direct representation for ranges between two times. Periods provide the ability to simplify some types of calculations by simplifying the conditional logic of the program.
The time periods example provides an example of using time periods.

Header

      #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o
      or
      #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types

Construction
Syntax	Description	Example
time_period(ptime begin, ptime end)	Create a period as [begin, end). If last is <= begin then the period will be defined as null.	date d(2002,Jan,01); ptime t(d, seconds(10)); //10 sec after midnight time_period tp(t, hours(3));
time_period(ptime start, time_duration len)	Create a period as [begin, begin+len). If len is <= zero then the period will be defined as null.	date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2);
time_period(time_period rhs)	Copy constructor	time_period tp1(tp)

Accessors
Syntax	Description	Example
ptime begin() const	Return first time of period.	date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.begin() --> 2002-Jan-01 00:00:10
ptime last() const	Return last time in the period	date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.last() --> 2002-Jan-01 09:59:59.999999999
ptime end() const	Return one past the last in period	date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.last() --> 2002-Jan-01 10:00:00
time_duration length() const	Return the length of the time period.	date d(2002,Jan,01); ptime t1(d); //midnight time_period tp(t1, hours(1)); tp.length() --> 1 hour
bool is_null() const	True if period is not well formed. eg: start less than end
bool contains(ptime) const	True if ptime is within the period	date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight ptime t3(d, hours(2)); //2 hours after midnight time_period tp(t1, t2); tp.contains(t3) --> true
bool contains(time_period) const	True if period is within the period	time_period tp1(ptime(d,hours(1)), ptime(d,hours(12))); time_period tp2(ptime(d,hours(2)), ptime(d,hours(4))); tp1.contains(tp2) --> true tp2.contains(tp1) --> false
bool intersects(time_period) const	True if periods overlap	time_period tp1(ptime(d,hours(1)), ptime(d,hours(12))); time_period tp2(ptime(d,hours(2)), ptime(d,hours(4))); tp2.intersects(tp1) --> true
time_period intersection(time_period) const	Calculate the intersection of 2 periods. Null if no intersection.
time_period merge(time_period) const	Returns union of two periods. Null if no intersection.
time_period span(time_period) const	Combines two periods and any gap between them such that start = min(p1.start, p2.start) and end = max(p1.end , p2.end).
time_period shift(date_duration)	Add duration to both start and end.

Conversion To String
Syntax	Description	Example
std::string to_simple_string(time_period dp)	To [YYYY-mmm-DD hh:mm:ss.fffffffff/YYYY-mmm-DD hh:mm:ss.fffffffff] string where mmm is 3 char month name.	[2002-Jan-01 01:25:10.000000001/2002-Jan-31 01:25:10.123456789]

Operators
Syntax	Description	Example
operator<<	Output streaming operator for time duration. Uses facet to output [date time_of_day/date time_of_day]. The default is format is [YYYY-mmm-DD hh:mm:ss.fffffffff/YYYY-mmm-DD hh:mm:ss.fffffffff] string where mmm is 3 char month name.	[2002-Jan-01 01:25:10.000000001/2002-Jan-31 01:25:10.123456789]
operator==, operator!=	Equality operators. Periods are equal if p1.begin == p2.begin && p1.last == p2.last	if (tp1 == tp2) {...
operator<	Ordering with no overlap. True if tp1.end() less than tp2.begin()	if (tp1 < tp2) {...
operator>	Ordering with no overlap. True if tp1.begin() greater than tp2.end()	if (tp1 > tp2) {... etc
operator<=, operator>=	Defined in terms of the other operators.
top

Time Iterators
Introduction -- Header -- Overview -- Operators

Introduction
Time iterators provide a mechanism for iteration through times. Time iterators are similar to Bidirectional Iterators. However, time_iterators are different than standard iterators in that there is no underlying sequence, just a calculation function. In addition, time_iterators are directly comparable against instances of class ptime. Thus a second iterator for the end point of the iteration is not required, but rather a point in time can be used directly. For example, the following code iterates using a 15 minute iteration interval. The print hours example also illustrates the use of the time_iterator.

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


	int
	main()
	{
	  using namespace boost::gregorian;
	  using namespace boost::posix_time;
	  date d(2000,Jan,20);
	  ptime start(d);
	  ptime end = start + hours(1);
	  time_iterator titr(start,minutes(15)); //increment by 15 minutes
	  //produces 00:00:00, 00:15:00, 00:30:00, 00:45:00
	  while (titr < end) {
	    std::cout << to_simple_string(*titr) << std::endl;
	    ++titr;
	  }
	  std::cout << "Now backward" << std::endl;
	  //produces 01:00:00, 00:45:00, 00:30:00, 00:15:00
	  while (titr > start) {
	    std::cout << to_simple_string(*titr) << std::endl;
	    --titr;
	  }
	}

Header

      #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o
      or
      #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types

Overview
Class	Construction Parameters	Description
time_iterator	ptime start_time, time_duration increment	Iterate incrementing by the specified duration.

Operators
Syntax	Description	Example
operator==(const ptime& rhs), operator!=(const ptime& rhs), operator>, operator< operator>=, operator<=	A full complement of comparison operators	date d(2002,Jan,1); ptime start_time(d, hours(1)); //increment by 10 minutes time_iterator titr(start_time, minutes(10)); ptime end_time = start_time + hours(2); if (titr == end_time) // false if (titr != end_time) // true if (titr >= end_time) // false if (titr <= end_time) // true
prefix increment	Increment the iterator by the specified duration.	//increment by 10 milli seconds time_iterator titr(start_time, milliseconds(10)); ++titr; // == start_time + 10 milliseconds
prefix decrement	Decrement the iterator by the specified time duration.	Example time_iterator titr(start_time, time_duration(1,2,3)); --titr; // == start_time - 1 hour, 2 minutes, and 3 seconds
top

Local Time Adjustment
Introduction -- Header -- Overview

Introduction
A frequent problem in time representation is the conversion between various local time systems. In general this is accomplished by using a reference time system. The reference time system is typically UTC.
Since the posix_time system does no internal time adjustment it can be used to represent both local times and UTC times. However, the user is currently left to handle conversions and time zone knowledge explicitly.
The library offers two different ways to perform UTC to local conversions. The first is using the time zone settings of the computer. This is a useful solution for converting a UTC time for a user machine. This approach depends on the ctime API and will provide incorrect results if the environment is set incorrectly. The other approach allows conversion from any zone to UTC and back independent of the settings of the time zone settings of the computer. The local utc conversion example demonstrates both of these techniques.

Header

      #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o
      or
      #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types

Overview
Class	Description	Example
date_time::c_local_adjustor<ptime>::utc_to_local(ptime)	Calculate local machine time from a UTC time based on time zone settings and the C API.	typedef boost::date_time::c_local_adjustor<ptime> local_adj; ptime t10(date(2002,Jan,1), hours(7)); ptime t11 = local_adj::utc_to_local(t10);
date_time::local_adjustor<ptime, utc_offset, dst_rules>::utc_to_local(ptime)	Calculate local machine time from a UTC time based daylight savings rules and utc offset	example
date_time::local_adjustor<ptime, utc_offset, dst_rules>::local_to_utc(ptime)	Calculate UTC time based on daylight savings rules and utc offset.	example
top

Details

Calculations
Timepoints -- Durations -- Intervals (Periods) -- Special Value Handling

Timepoints
This section describes some of basic arithmetic rules that can be performed with timepoints. In general, Timepoints support basic arithmetic in conjunction with Durations as follows:

      Timepoint + Duration  --> Timepoint
      Timepoint - Duration  --> Timepoint
      Timepoint - Timepoint --> Duration

Unlike regular numeric types, the following operations are undefined:

      Duration + Timepoint  --> Undefined
      Duration - Timepoint  --> Undefined
      Timepoint + Timepoint --> Undefined

Durations
Durations represent a length of time and can have positive and negative values. It is frequently useful to be able to perform calculations with other durations and with simple integral values. The following describes these calculations:

      Duration + Duration  --> Duration
      Duration - Duration  --> Duration
      
      Duration * Integer   --> Duration
      Integer  * Duration  --> Duration
      Duration / Integer   --> Duration  (Integer Division rules)

Intervals (Periods)
Interval logic is extremely useful for simplifying many 'calculations' for dates and times. The following describes the operations provided by periods which are based on half-open range. The following operations calculate new time periods based on two input time periods:

      Timeperiod intersection Timeperiod --> Timeperiod (null interval if no intersection)
      Timeperiod merge Timeperiod        --> Timeperiod (null interval if no intersection)
      Timeperiod shift Duration          --> Timeperiod (shift start and end by duration amount)

In addition, periods support various queries that calculate boolean results. The first set is caluculations with other time periods:

      Timeperiod == Timeperiod           --> bool
      Timeperiod < Timeperiod            --> bool (true if lhs.last <= rhs.begin)
      Timeperiod intersects Timeperiod   --> bool
      Timeperiod contains Timeperiod     --> bool
      Timeperiod is_adjacent Timeperiod  --> bool

The following calculations are performed versus the Timepoint.

      Timeperiod contains Timepoint      --> bool
      Timeperiod is_before Timepoint     --> bool
      Timeperiod is_after Timepoint      --> bool

Special Value Handling
For many temporal problems it is useful for Duration and Timepoint types to support special values such as Not A Date Time (NADT) and infinity. In general special values such as Not A Date Time (NADT) and infinity should follow rules like floating point values. Note that it should be possible to configure NADT based systems to throw an exception instead of result in NADT.

      Timepoint(NADT) + Duration --> Timepoint(NADT)
      Timepoint(∞) + Duration    --> Timepoint(∞)
      Timepoint + Duration(∞)    --> Timepoint(∞)
      Timepoint - Duration(∞)    --> Timepoint(-∞)

When performing operations on both positive and negative infinities, the library will produce results consistent with the following.

      Timepoint(+∞) + Duration(-∞) --> NADT
      Duration(+∞) + Duration(-∞)  --> NADT
      Duration(±∞) * Zero          --> NADT
      
      Duration(∞) * Integer(Not Zero) --> Duration(∞)
      Duration(+∞) * -Integer         --> Duration(-∞)
      Duration(∞) / Integer           --> Duration(∞)

Design Goals
Category	Description	Functions
Interfaces	Provide concrete classes for manipulation of dates and times	date, time, date_duration, time_duration, date_period, time_period, etc support for infinity - positive infinity, negative infinity iterators over time and date ranges allow date and time implementations to be separate as much as possible
Calculation	Provide a basis for performing efficient time calculations	days between dates durations of times durations of dates and times together
Representation Flexibility	Provide the maximum possible reusability and flexibility	traits based customization of internal representations for size versus resolution control Allowing the use of different epochs and resolution (eg: seconds versus microseconds, dates starting at the year 2000 versus dates starting in 1700) Options for configuring unique calendar representations (Gregorian + others) the use of Julian Day number and the conversion between this and the Gregorian/Julian calendar date Allow for flexible adjustments including leap seconds
Date Calculations	Provide tools for date calculations	provide basis for calculation of complex event specs like holidays calendar to calendar conversions provide for ability to extend to new calendar systems
Time Calculations	Provide concrete classes for manipulation of time	provide the ability to handle cross time-zone issues provide adjustments for daylight savings time (summer time)
Clock Interfaces	Provide classes for retrieving time current time	access to a network / high resolution time sources retrieving the current date time information to populate classes
I/O Interfaces	Provide input and output for time including	multi-lingual support provide ISO8601 compliant time facet use I/O facets for different local behavior

Tradeoffs: Stability, Predictability, and Approximations

Unavoidable Trade-offs
The library does its best to provide everything a user could want, but there are certain inherent constraints that limit what any temporal library can do. Specifically, a user must choose which two of the following three capabilities are desired in any particular application:
exact agreement with wall-clock time
accurate math, e.g. duration calculations
ability to handle timepoints in the future
Some libraries may implicitly promise to deliver all three, but if you actually put them to the test, only two can be true at once. This limitation is not a deficiency in the design or implementation of any particular library; rather it is a consequence of the way different time systems are defined by international standards. Let's look at each of the three cases:
If you want exact agreement with wall-clock time, you must use either UTC or local time. If you compute a duration by subtracting one UTC time from another and you want an answer accurate to the second, the two times must not be too far in the future because leap seconds affect the count but are only determined about 6 months in advance. With local times a future duration calculation could be off by an entire hour, since legislatures can and do change DST rules at will.
If you want to handle wall-clock times in the future, you won't be able (in the general case) to calculate exact durations, for the same reasons described above.
If you want accurate calculations with future times, you will have to use TAI or an equivalent, but the mapping from TAI to UTC or local time depends on leap seconds, so you will not have exact agreement with wall-clock time.

Stability, Predictability, and Approximations
Here is some underlying theory that helps to explain what's going on. Remember that a temporal type, like any abstract data type (ADT), is a set of values together with operations on those values.

Stability
The representation of a type is stable if the bit pattern associated with a given value does not change over time. A type with an unstable representation is unlikely to be of much use to anyone, so we will insist that any temporal library use only stable representations.
An operation on a type is stable if the result of applying the operation to a particular operand(s) does not change over time.

Predictability
Sets are most often classified into two categories: well-defined and ill-defined. Since a type is a set, we can extend these definitions to cover types. For any type T, there must be a predicate is_member( x ) which determines whether a value x is a member of type T. This predicate must return true, false, or dont_know.
If for all x, is_member( x ) returns either true or false, we say the set T is well-defined.
If for any x, is_member( x ) returns dont_know, we say the set T is ill-defined.
Those are the rules normally used in math. However, because of the special characteristics of temporal types, it is useful to refine this view and create a third category as follows:
For any temporal type T, there must be a predicate is_member( x, t ) which determines whether a value x is a member of T. The parameter t represents the time when the predicate is evaluated. For each xi, there must be a time ti and a value v such that:
v = true or v = false, and
for all t < ti, is_member( xi, t ) returns dont_know, and
for all t >= ti, is_member( xi, t ) returns v.
ti is thus the time when we "find out" whether xi is a member of T. Now we can define three categories of temporal types:
If for all xi, ti = negative infinity, we say the type T is predictable.
If for some xi, ti = positive infinity, we say the type T is ill-formed.
Otherwise we say the type T is unpredictable (this implies that for some xi, ti is finite).
Ill-formed sets are not of much practical use, so we will not discuss them further. In plain english the above simply says that all the values of a predictable type are known ahead of time, but some values of an unpredictable type are not known until some particular time.

Stability of Operations
Predictable types have a couple of important properties:
there is an order-preserving mapping from their elements onto a set of consecutive integers, and
duration operations on their values are stable
The practical effect of this is that duration calculations can be implemented with simple integer subtraction. Examples of predictable types are TAI timepoints and Gregorian dates.
Unpredictable types have exactly the opposite properties:
there is no order-preserving mapping from their elements onto a set of consecutive integers, and
duration operations on their values are not stable.
Examples of unpredictable types are UTC timepoints and Local Time timepoints.
We can refine this a little by saying that a range within an unpredicatable type can be predictable, and operations performed entirely on values within that range will be stable. For example, the range of UTC timepoints from 1970-01-01 through the present is predictable, so calculations of durations within that range will be stable.

Approximations
These limitations are problematical, because important temporal types like UTC and Local Time are in fact unpredictable, and therefore operations on them are sometimes unstable. Yet as a practical matter we often want to perform this kind of operation, such as computing the duration between two timepoints in the future that are specified in Local Time.
The best the library can do is to provide an approximation, which is generally possible and for most purposes will be good enough. Of course the documentation must specify when an answer will be approximate (and thus unstable) and how big the error may be. In many respects calculating with unpredictable sets is analogous to the use of floating point numbers, for which results are expected to only be approximately correct. Calculating with predictable sets would then be analogous to the user of integers, where results are expected to be exact.
For situations where exact answers are required or instability cannot be tolerated, the user must be able to specify this, and then the library should throw an exception if the user requests a computation for which an exact, stable answer is not possible.

Serialization
The boost::date_time library is compatible with the boost::serialization library's text and xml archives. The list of classes that are serializable are:

boost::gregorian
date	date_duration	date_period
partial_date	nth_day_of_week_in_month	first_day_of_week_in_month
last_day_of_week_in_month	first_day_of_week_before	first_day_of_week_after
greg_month	greg_day	greg_weekday

boost::posix_time
ptime	time_duration	time_period
No extra steps are required to build the date_time library for serialization use.
Example text_archive usage:

      using namespace boost::posix_time;
      using namespace boost::gregorian;
      ptime pt(date(2002, Feb, 14)), hours(10)), pt2(not_a_date_time);
      std::ofstream ofs("tmp_file");
      archive::test_oarchive oa(ofs);
      oa << pt;                        // NOTE: no macro
      ofs.close();
      std::ifstream ifs("tmp_file");
      archive::text_iarchive ia(ifs);
      ia >> pt2;                       // NOTE: no macro
      ifs.close();
      pt == pt2; // true

Example xml_archive usage:

      using namespace boost::gregorian;
      date d(2002, Feb, 14), d2(not_a_date_time);
      std::ofstream ofs("tmp_file");
      archive::xml_oarchive oa(ofs);
      oa << BOOST_SERIALIZATION_NVP(d); // macro required for xml_archive
      ofs.close();
      std::ifstream ifs("tmp_file");
      archive::xml_iarchive ia(ifs);
      ia >> BOOST_SERIALIZATION_NVP(d2); // macro required for xml_archive
      ifs.close();
      d == d2; // true

To use the date_time serialization code, the proper header files must be explicitly included. The header files are:

      boost/date_time/gregorian/greg_serialize.hpp

and

      boost/date_time/posix_time/time_serialize.hpp

Terminology
The following are a number of terms relevant to the date-time domain.
A taxonomy of temporal types:
Timepoint -- Specifier for a location in the time continuum. Similar to a number on a ruler.
Timelength -- A duration of time unattached to any point on the time continuum.
Timeinterval -- A duration of time attached to a specific point in the time continuum.
And some other terms:
Accuracy -- A measure of error, the difference between the reading of a clock and the true time.
Calendar System -- A system for labeling time points with day level resolution.
Clock Device -- A software component (tied to some hardware) that provides the current date or time with respect to a calendar or clock system.
Precision -- A measure of repeatability of a clock.
Resolution -- A specification of the smallest representable duration (eg: 1 second, 1 century) for a clock/calendar system or temporal type.
Stability -- The property of a class which says that the underlying representation (implementation) associated with a particular (abstract) value will never change.
Time System -- A system for labeling time points with higher resolution than day-level.
Some standard date-time terminology:
Epoch -- Starting time point of a calendar or clock system.
DST -- Daylight savings time - a local time adjustment made in some regions during the summer to shift the clock time of the daylight hours
Time zone -- A region of the earth that provides for a 'local time' defined by DST rules and UT offset.
UTC Time -- Coordinated Universal Time - Civil time system as measured at longitude zero. Kept adjusted to earth rotation by use of leap seconds. Also known as Zulu Time. Replaced the similar system known as Greenwich Mean Time. For more see
TAI Time -- A high-accuracy monotonic (need better term) time system measured to .1 microsecond resolution by atomic clocks around the world. Not adjusted to earth rotation. For more see
Some more experimental ones:
Local Time -- A time measured in a specific location of the universe.
Time Label -- A tuple that either completely or partially specifies a specific date-time with respect to a calendar or clock system. This is the year-month-day representation.
Adjusting Time Length -- A duration that represents varying physical durations depending on the moment in time. For example, a 1 month duration is typically not a fixed number of days and it depends on the date it is measured from to determine the actual length.
These are design sorts of terms:
Generation function -- A function that generates a specific set of time points, lengths, or intervals based on one or more parameters.

References
Date References
Time References
Other C/C++ Libraries
JAVA Date-Time Libraries
Scripting Language Libraries
Related Commercial and Fanciful Pages
Resolution, Precision, and Accuracy

Date Calendar References
ISO 8601 date time standard -- Summary by Markus Kuhn
Calendrical Calculations book by Reingold & Dershowitz
Calendar FAQ by Claus Tøndering
Calendar zone
XML schema for date time
Will Linden's Calendar Links
XMAS calendar melt

Time
Martin Folwer on time patterns
Recurring Events for Calendars
Patterns for things that Change with time
US National Institute of Standards and Technology Time Exhibits
Network Time Protocol at NTP.org
US Navy Systems of Time
International Atomic Time
Date-Time type PostgreSQL User Guide

Other C/C++ Libraries
ctime C Standard library reference at cplusplus.com
XTime C extension proposal
Another C library extension proposal by David Tribble
libTAI is a C based time library
Time Zone Database C library for managing timezones/places
International Components for Unicode by IBM (open source)
Calendar Class
Date Time Services
Time Zone Class
Date-Time Formatting
Julian Library in C by Mark Showalter -- NASA

JAVA Date & Time Library Quick Reference
Calendar class
Gregorian calendar
Date class
sql.time class
Date format symbols
Date format
Simple Date Format
Simple Time Zone

Scripting Language Libraries
A python date library MX Date Time
Perl date-time
Date-Time packages at CPAN
Date::Calc at CPAN
Date::Convert calendar conversions at CPAN
A PHP library Vlib Date Library

Related Commercial and Fanciful Pages
Leapsecond.com time page
World Time Server / TZ database
10000 year clock at Long Now Foundation
Timezones for PCs

Resolution, Precision, and Accuracy
Definitions with pictures from Agilent Technologies
Another set of pictures from Team Labs
Definitions from Southampton Institute
Definitions from Newport Corporation in the context of instrumentation

Build-Compiler Information
Overview -- Compilation Options -- Compiler/Portability Notes -- Directory Structure -- Required Boost Libraries

Overview
The library has several functions that require the creation of a library file. The Jamfile in the build directory will produce a "static" library (libboost_date_time) and a "dynamic/shared" library (boost_date_time) that contains these functions.

Compilation Options
By default the posix_time system uses a 64 bit integer and a 32 bit integer internally to provide nano-second level resolutions. As an alternative, a single 64 bit integer can be used to provide a microsecond level resolution. This alternative implementation may provide better performance and more compact memory usage for many applications that do not require nano-second resolutions.
To use the alternate resolution (64 bit microsecond) the variable BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG must be defined in the library users project files (ie Makefile, Jamfile, etc). This macro is not used by the Gregorian system and therefore has no effect when building the library.

Compiler/Portability Notes
The Boost Date-Time library has been built and tested with many compilers. However, some compilers and standard libraries have issues. While some of these issues can be worked around, others are difficult to work around. The following compilers fully support all aspects of the library:
GCC 3.2-7 on Linux
GCC 2.95.3 with STLport-4.5.3 on Linux
GCC 3.1 (cygwin)
MSVC 7.1
In particular, a lack of support for standard locales limits the ability of the library to support iostream based input output. For these compilers a set of more limited string based input-output is provided. The compilers/standard libraries with this limitation include:
GCC 2.9x on Linux
Borland 5.1.1 and 5.6
MSVC 6 SP5
Other compilers such as Comeau and Metroworks have been tested successfully with earlier versions of the library.

Directory Structure
The directory tree has the following structure:

      /boost/date_time                    -- common headers and template code
      /boost/date_time/gregoran           -- Gregorian calendar system header files
      /boost/date_time/posix_time         -- posix time system headers
      /libs/date_time/build               -- build files and output directory
      /libs/date_time/test                -- test battery for generic code
      /libs/date_time/test/gregorian      -- test battery for the Gregorian system
      /libs/date_time/test/posix_time     -- test battery for the posix_time system
      /libs/date_time/examples/posix_time -- time example programs
      /libs/date_time/examples/gregorian  -- nifty example programs
      /libs/date_time/src/gregorian       -- cpp files for libboost_date_time
      /libs/date_time/src/posix_time      -- empty (one file, but no source code...)

Required Boost Libraries
The library depends on
boost.tokenizer
boost.integer(cstdint)
boost.operators
boost::lexical_cast
so at least these libraries need to be installed.

Tests
The library provides a large number of tests in the

      libs/date_time/test
      libs/date_time/test/gregorian
      libs/date_time/test/posix_time

directories. Building and executing these tests assures that the installation is correct and that the library is functioning correctly. In addition, these tests facilitate the porting to new compilers. Finally, the tests provide examples of many functions not explicitly described in the usage examples.

Change History

Changes from Boost 1.31 to 1.32 (date_time 1.02 to 1.03)
Type	Description
Bug Fix	Snap to end of month behavior corrected for year_functor. Previously, starting from 2000-Feb-28 (leap year and not end of month) and iterating through the next leap year would result in 2004-Feb-29 instead of 2004-Feb-28. This behavior has been corrected to produce the correct result of 2004-Feb-28. Thanks to Bart Garst for this change.
Feature	Free function for creating a ptime object from a FILETIME struct. This function is only available on platforms that define BOOST_HAS_FTIME.
Feature	Microsecond time clock is now available on most windows compilers as well as Unix.
Feature	Use of the boost::serialization library is now available with most of the date_time classes. Classes capable of serialization are: date_generator classes, date, days, date_period, greg_month, greg_weekday, greg_day, ptime, time_duration, and time_period. Thanks to Bart Garst for this change.
Feature	Functions added to convert date and time classes to wstring. The library now provides to_*_wstring as well as to_*_string functions for: simple, iso, iso_extended, and sql for dates and compilers that support wstrings. Thanks to Bart Garst for this change.
Feature	Period classes now handle zero length and NULL periods correctly. A NULL period is a period with a negative length. Thanks to Frank Wolf and Bart Garst for this change.
Feature	Added end_of_month function to gregorian::date to return the last day of the current month represented by the date. Result is undefined for not_a_date_time or infinities.
Bug Fix	Removed incorrect usage of BOOST_NO_CWCHAR macro throughout library.
Feature	New names added for some date classes. Original names are still valid but may some day be deprecated. Changes are: date_duration is now days nth_kday_of_month is now nth_day_of_the_week_in_month first_kday_of_month is now first_day_of_the_week_in_month last_kday_of_month is now last_day_of_the_week_in_month first_kday_after is now first_day_of_the_week_after first_kday_before is now first_day_of_the_week_before
Feature	Free functions for date generators added. Functions are: days_until_weekday, days_before_weekday, next_weekday, and previous_weekday. days days_until_weekday(date, greg_weekday); days days_before_weekday(date, greg_weekday); date next_weekday(date, greg_weekday); date previous_weekday(date, greg_weekday); Thanks to Bart Garst for this change.
Feature	New experimental duration types added for months, years, and weeks. These classes also provide mathematical operators for use with date and time classes. Be aware that adding of months or years a time or date past the 28th of a month may show non-normal mathematical properties. This is a result of 'end-of-month' snapping used in the calculation. The last example below illustrates the issue. months m(12); years y(1); m == y; // true days d(7); weeks w(1); d == w; // true ptime t(...); t += months(3); date d(2004,Jan,30); d += months(1); //2004-Feb-29 d -= months(1); //2004-Jan-29 Input streaming is not yet implemented for these types. Thanks to Bart Garst for this change.
Feature	Unifying base class for date_generators brought in to gregorian namespace. See Print Holidays Example.
Feature	Added constructors for date and ptime that allow for default construction (both) and special values construction (ptime, both now support this). Default constructors initialize the objects to not_a_date_time (NADT). ptime p_nadt(not_a_date_time), p_posinf(pos_infin); ptime p; // p == NADT date d; // d == NADT Thanks to Bart Garst for this change.
Feature	Output streaming now supports wide stream output on compiler / standard library combinations that support wide streams. This allows code like: std::wstringstream wss; date d(2003,Aug,21); wss << d; Thanks to Bart Garst for this change.
Feature	Input streaming for date and time types is now supported on both wide and narrow streams: date d(not_a_date_time); std::stringstream ss("2000-FEB-29"); ss >> d; //Feb 29th, 2000 std::wstringstream ws("2000-FEB-29"); ws >> d; //Feb 29th, 2000 Thanks to Bart Garst for this change.
Bug Fix	Fixed bug in duration_from_string() where a string formatted with less than full amount of fractional digits created an incorrect time_duration. With microsecond resolution for time durations the string "1:01:01.010" created a time duration of 01:01:01.000010 instead of 01:01:01.010000
Bug Fix	Fixed the special value constructor for gregorian::date and posix_time::ptime when constructing with min_date_time or max_date_time. The wrong value was constructed for these.

Changes from Boost 1.30 to 1.31 (date_time 1.01 to 1.02)
Type	Description
Bug Fix	Build configuration updated so dll, statically, and dynamically linkable library files are now produced with MSVC compilers. See Build/Compiler Information for more details.
Bug Fix	Time_duration from_string is now correctly constructed from a negative value. (ie "-0:39:00.000") Code provided by Bart Garst.
Bug Fix	Fixed many MSVC compiler warnings when compiled with warning level 4.
Feature	Added prefix decrement operator (--) for date and time iterators. See Time Iterators and Date Iterators for more details. Code provided by Bart Garst.
Feature	Special_values functionality added for date_duration, time_duration and time classes. Code provided by Bart Garst.
Bug Fix	Fixed time_duration_traits calculation bug which was causing time duration to be limited to 32bit range even when 64 bits were available. Thanks to Joe de Guzman for tracking this down.
Bug Fix	Provided additional operators for duration types (eg: date_duration, time_duration). This includes dividable by integer and fixes to allow +=, -= operators. Thanks to Bart Garst for writing this code. Also, the documentation of Calculations has been improved.
Bug Fix	Added typedefs to boost::gregorian gregorian_types.hpp various date_generator function classes.
Feature	Added from_time_t function to convert time_t to a ptime.
Feature	Added a span function for combining periods. See date period and time period docs.
Feature	Added a function to time_duration to get the total number of seconds in a duration truncating any fractional seconds. In addition, other resolutions were added to allow for easy conversions. For example seconds(1).total_milliseconds() == 1000 seconds(1).total_microseconds() == 1000000 hours(1).total_milliseconds() == 3600*1000 //3600 sec/hour seconds(1).total_nanoseconds() == 1000000000
Feature	Added output streaming operators for the date generator classes - partial_date, first_kday_after, first_kday_before, etc. Thanks to Bart Garst for this work.
Feature	Added unary- operators for durations for reversing the sign of a time duration. For example: time_duration td(5,0,0); //5 hours td = -td; //-5 hours Thanks to Bart Garst for this work.
Feature	Added support for parsing strings with 'month names'. Thus creating a date object from string now accepts multiple formats ("2003-10-31","2003-Oct-31", and "2003-October-31"). Thus, date d = from_simple_string("2003-Feb-27") is now allowed. A bad month name string ( from_simple_string("2003-SomeBogusMonthName-27")) will cause a bad_month exception. On most compilers the string compare is case insensitive. Thanks to Bart Garst for this work.
Feature	In addition to support for month names or numbers, functions have been added to create date objects from multi-ordered date strings. Ex: "January-21-2002", "2002-Jan-21", and "21-Jan-2003". See Date Class for more details.
Bug-Fix	Various documentation fixes. Thanks to Bart Garst for updates.

Changes from Boost 1.29 to 1.30 (date_time 1.00 to 1.01)
Notice: The interface to the partial_date class (see date_algorithms) was changed. The order of construction parameters was changed which will cause some code to fail execution. This change was made to facilitate more generic local time adjustment code. Thus instead of specifying partial_date pd(Dec,25) the code needs to be changed to partial_date pd(25, Dec);
Type	Description
Bug Fix	Added new experimental feature for Daylight Savings Time calculations. This allows traits based specification of dst rules.
Feature	Added new interfaces to calculate julian day and modified julian day to the gregorian date class. See boost::gregorian::date.
Feature	Add new interface to calculate iso 8601 week number for a date. See boost::gregorian::date.
Feature	Add an iso 8601 time date-time format (eg: YYYYMMDDTHHHMMSS) parsing function. See Class ptime for more information.
Feature	Added a length function to the period template so that both date_periods and time_periods will now support this function.
Bug Fix	Split Jamfiles so that libs/date_time/build/Jamfile only builds library and /libs/date_time/libs/test/Jamfile which runs tests.
Bug Fix	Fixed many minor documentation issues.
Bug Fix	Removed the DATE_TIME_INLINE macro which was causing link errors. This macro is no longer needed in projects using the library.
Bug Fix	Added missing typedef for year_iterator to gregorian_types.hpp
Bug Fix	Fixed problem with gregorian ostream operators that prevented the use of wide streams.
Bug-Fix	Tighten error handling for dates so that date(2002, 2, 29) will throw a bad_day_of_month exception. Previously the date would be incorrectly constructed. Reported by sourceforge bug: 628054 among others.

Acknowledgements
Many people have contributed to the development of this library. In particular Hugo Duncan and Joel de Guzman for help with porting to various compilers. For initial development of concepts and design Corwin Joy and Michael Kenniston deserve special thanks. Also extra thanks to Michael for writing up the theory and tradeoffs part of the documentation. Dave Zumbro for initial inspiration and sage thoughts. Many thanks to boost reviewers and users including: William Seymour, Kjell Elster, Beman Dawes, Gary Powell, Andrew Maclean, William Kempf, Peter Dimov, Chris Little, David Moore, Darin Adler, Gennadiy Rozental, Joachim Achtzehnter, Paul Bristow, Jan Langer, Mark Rodgers, Glen Knowles, Matthew Denman, and George Heintzelman.

Examples

General Usage Examples
The following provides some sample usage of dates. See Date Programming for more details.

    
	 using namespace boost::gregorian; 
	 date weekstart(2002,Feb,1);
	 date weekend  = weekstart + week(1);
	 date d2 = d1 + days(5);
	 date today = day_clock::local_day();
	 if (d2 >= today) {} //date comparison operators
	 
	 date_period thisWeek(d1,d2);
	 if (thisWeek.contains(today)) {}//do something
	
	 //iterate and print the week
	 day_iterator itr(weekstart);
	 while (itr <= weekend) {
	   std::cout << (*itr) << std::endl;
           ++itr;
	 }  
         //input streaming
         std::stringstream ss("2004-Jan-1");
         ss >> d3;
        
         //localized i/o using facets
         std::locale global;
         std::locale german(global, 
                            new date_facet(de_short_month_names, 
                                           de_long_month_names,
                                           de_special_value_names,
                                           de_long_weekday_names,
                                           de_long_weekday_names,
                                           '.', 
                                           boost::date_time::ymd_order_dmy));
         std::cout.imbue(global2); 
         date d4(2002, Oct, 1);
         std::cout << d4; //01.Okt.2002

         //date generator functions
         date d5 = next_weekday(d4, Sunday); //calculate sunday following d4

         //define a shorthand for the nth_day_of_the_week_in_month function object
	 typedef nth_day_of_the_week_in_month nth_dow;
         //US labor day is first Monday in Sept
	 nth_dow labor_day(nth_dow::first,Monday, Sep); 
	 date d6 = labor_day.get_date(2004); //calculate a specific date from functor

The following provides some example code using times. See Time Programming for more details.

    
	 use namespace boost::posix_time; 
	 date d(2002,Feb,1); //an arbitrary date
	 ptime t1(d, hours(5)+nanosec(100)); //date + time of day offset
	 ptime t2 = t1 - minutes(4)+seconds(2);
	 ptime now = second_clock::local_time(); //use the clock
	 date today = now.date(); //Get the date part out of the time
	 date tommorrow = today + date_duration(1);
	 ptime tommorrow_start(tommorrow); //midnight 

         //input streaming
         std::stringstream ss("2004-Jan-1 05:21:33.20");
         ss >> t2;

	 //starting at current time iterator adds by one hour
	 time_iterator titr(now,hours(1)); 
	 for (; titr < tommorrow_start; ++titr) {
	   std::cout << (*titr) << std::endl;
	 }

top

Dates as Strings
Various parsing and output of strings.

    

      /* The following is a simple example that shows conversion of dates 
       * to and from a std::string.
       * 
       * Expected output:
       * 2001-Oct-09
       * 2001-10-09
       * Tuesday October 9, 2001
       * An expected exception is next: 
       * Exception: Month number is out of range 1..12
       */

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

      int
      main() 
      {

	using namespace boost::gregorian;

	try {
	  // The following date is in ISO 8601 extended format (CCYY-MM-DD)
	  std::string s("2001-10-9"); //2001-October-09
	  date d(from_simple_string(s));
	  std::cout << to_simple_string(d) << std::endl;
	  
	  //Read ISO Standard(CCYYMMDD) and output ISO Extended
	  std::string ud("20011009"); //2001-Oct-09
	  date d1(from_undelimited_string(ud));
	  std::cout << to_iso_extended_string(d1) << std::endl;
	  
	  //Output the parts of the date - Tuesday October 9, 2001
	  date::ymd_type ymd = d1.year_month_day();
	  greg_weekday wd = d1.day_of_week();
	  std::cout << wd.as_long_string() << " "
		    << ymd.month.as_long_string() << " "
		    << ymd.day << ", " << ymd.year
		    << std::endl;

	  //Let's send in month 25 by accident and create an exception
	  std::string bad_date("20012509"); //2001-??-09
	  std::cout << "An expected exception is next: " << std::endl;
	  date wont_construct(from_undelimited_string(bad_date));
	  //use wont_construct so compiler doesn't complain, but you wont get here!
	  std::cout << "oh oh, you shouldn't reach this line: " 
		    << to_iso_string(wont_construct) << std::endl;
	}
	catch(std::exception& e) {
	  std::cout << "  Exception: " <<  e.what() << std::endl;
	}


	return 0;
      }

top

Days Alive
Calculate the number of days you have been living using durations and dates.

    
      /* Short example that calculates the number of days since user was born.
       * Demonstrates comparisons of durations, use of the day_clock,
       * and parsing a date from a string.
       */

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

      int
      main() 
      {
	
	using namespace boost::gregorian;
	std::string s;
	std::cout << "Enter birth day YYYY-MM-DD (eg: 2002-02-01): ";
	std::cin >> s;
	try {
	  date birthday(from_simple_string(s));
	  date today = day_clock::local_day();
	  days days_alive = today - birthday;
	  days one_day(1);
	  if (days_alive == one_day) {
	    std::cout << "Born yesterday, very funny" << std::endl;
	  }
	  else if (days_alive < days(0)) {
	    std::cout << "Not born yet, hmm: " << days_alive.days() 
		      << " days" <<std::endl;
	  }
	  else {
	    std::cout << "Days alive: " << days_alive.days() << std::endl;
	  }

	}
	catch(...) {
	  std::cout << "Bad date entered: " << s << std::endl;
	}
	return 0;
      }

top

Days Between New Years
Calculate the number of days till new years

    
      /* Provides a simple example of using a date_generator, and simple
       * mathematical operatorations, to calculate the days since 
       * New Years day of this year, and days until next New Years day.
       *
       * Expected results:
       * Adding together both durations will produce 366 (365 in a leap year).
       */
      #include <iostream>
      #include "boost/date_time/gregorian/gregorian.hpp"

      int
      main() 
      {
	
	using namespace boost::gregorian;

	date today = day_clock::local_day();
	partial_date new_years_day(1,Jan);
	//Subtract two dates to get a duration
	days days_since_year_start = today - new_years_day.get_date(today.year());
	std::cout << "Days since Jan 1: " << days_since_year_start.days() 
		  << std::endl;
	
	days days_until_year_start = new_years_day.get_date(today.year()+1) - today;
	std::cout << "Days until next Jan 1: " << days_until_year_start.days() 
		  << std::endl;
	return 0;
      };

top

End of the Months
Iterates accross the remaining months in a given year, always landing on the last day of the month.

    
      /* Simple program that uses the gregorian calendar to find the last
       * day of the month and then display the last day of every month left 
       * in the year.
       */

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

      int
      main()
      {
	using namespace boost::gregorian;
	
	std::cout << "   Enter Year(ex: 2002): ";
	int year, month;
	std::cin >> year;
	std::cout << "   Enter Month(1..12): ";
	std::cin >> month;
	try {
	  int day = gregorian_calendar::end_of_month_day(year,month);
	  date end_of_month(year,month,day);

	  //Iterate thru by months --
	  month_iterator mitr(end_of_month,1);
	  date start_of_next_year(year+1, Jan, 1);
	  //loop thru the days and print each one
	  while (mitr < start_of_next_year){
	    std::cout << to_simple_string(*mitr) << std::endl;
	    ++mitr;
	  }

	}
	catch(...) {
	  std::cout << "Invalid Date Entered" << std::endl;
	}
	return 0;

      }

top

Localization Demonstration
The boost::date_time library provides the ability to create customized locale facets. Date ordering, language, seperators, and abbreviations can be customized.

    

      /* The following shows the creation of a facet for the output of 
       * dates in German (please forgive me for any errors in my German --
       * I'm not a native speaker).
       */

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

      /* Define a series of char arrays for short and long name strings to be 
       * associated with date output. */
      const char* const de_short_month_names[] = 
      {
	"Jan", "Feb", "Mar", "Apr", "Mai", "Jun",
	"Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "NAM" 
      };
      const char* const de_long_month_names[] =
      {
	"Januar", "Februar", "Marz", "April", "Mai",
	"Juni", "Juli", "August", "September", "Oktober",
	"November", "Dezember", "NichtDerMonat"
      };
      const char* const de_special_value_names[] =
      {
	"NichtDatumzeit", "-unbegrenztheit", "+unbegrenztheit"
      };
      const char* const de_long_weekday_names[] = 
      {
	"Sonntag", "Montag", "Dienstag", "Mittwoch",
	"Donnerstag", "Freitag", "Samstag"
      };
      const char* const de_short_weekday_names[] =
      {
	"Son", "Mon", "Die","Mit", "Don", "Fre", "Sam"
      };

      const char* const us_short_month_names[] = 
      {
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "NAD"
      };
      const char* const us_long_month_names[] =
      {
	"January", "February", "March", "April", "May",
	"June", "July", "August", "September", "October",
	"November", "December", "Not-A-Date"
      };
      const char* const us_special_value_names[] =
      { 
	"Not-A-Date", "-infinity", "+infinity"
      };
      const char* const us_long_weekday_names[] =
      {
	"Sunday", "Monday", "Tuesday", "Wenesday", 
	"Thursday", "Friday", "Saturday"
      };
      const char* const us_short_weekday_names[] =
      {
	"Sun", "Mon", "Tue","Wed", "Thu", "Fri", "Sat"
      };


      int
      main() 
      {

      #ifndef BOOST_DATE_TIME_NO_LOCALE

	using namespace boost::gregorian;
	typedef boost::date_time::all_date_names_put<greg_facet_config> date_facet;
	
	//create a new local
	std::locale default_locale;
	std::locale german_dates1(default_locale, 
				  new date_facet(de_short_month_names, 
						 de_long_month_names,
						 de_special_value_names,
						 de_short_weekday_names,
						 de_long_weekday_names,
						 '.',
						 boost::date_time::ymd_order_dmy,
						 boost::date_time::month_as_integer));
	
	date d1(2002, Oct, 1);
	std::cout.imbue(german_dates1); 
	// output the date in German using short month names
	std::cout << d1 << std::endl; //01.10.2002
	
	std::locale german_dates2(default_locale, 
				  new date_facet(de_short_month_names, 
						 de_long_month_names,
						 de_special_value_names,
						 de_short_weekday_names,
						 de_long_weekday_names,
						 '.',
						 boost::date_time::ymd_order_dmy,
						 boost::date_time::month_as_long_string));
	
	std::cout.imbue(german_dates2); 
	greg_month m = d1.month();
	std::cout << m << std::endl; //Oktober
	
	greg_weekday wd = d1.day_of_week();
	std::cout << wd << std::endl; //Dienstag


	//Numeric date format with US month/day/year ordering
	std::locale usa_dates1(default_locale, 
			       new date_facet(us_short_month_names, 
					      us_long_month_names,
					      us_special_value_names,
					      us_short_weekday_names,
					      us_long_weekday_names,
					      '/',
					      boost::date_time::ymd_order_us,
					      boost::date_time::month_as_integer));
	
	std::cout.imbue(usa_dates1); 
	std::cout << d1 << std::endl; //  10/01/2002
	//English names, iso order (year-month-day), '-' separator
	std::locale usa_dates2(default_locale, 
			       new date_facet(us_short_month_names, 
					      us_long_month_names,
					      us_special_value_names,
					      us_short_weekday_names,
					      us_long_weekday_names,
					      '-',
					      boost::date_time::ymd_order_iso,
					      boost::date_time::month_as_short_string));

	std::cout.imbue(usa_dates2); 
	std::cout << d1 << std::endl; //  2002-Oct-01
	
	
      #else 
	std::cout << "Sorry, localization is not supported by this compiler/library" 
		  << std::endl;
      #endif
	return 0;

      }

top

Date Period Calculations
Calculates if a date is in an 'irregular' collection of periods using period calculation functions.

    
      /*
      This example demonstrates a simple use of periods for the calculation
      of date information.

      The example calculates if a given date is a weekend or holiday
      given an exclusion set.  That is, each weekend or holiday is
      entered into the set as a time interval.  Then if a given date
      is contained within any of the intervals it is considered to
      be within the exclusion set and hence is a offtime.

      Output:
      Number Excluded Periods: 5
      20020202/20020203
      20020209/20020210
      20020212/20020212
      20020216/20020217
      In Exclusion Period: 20020216 --> 20020216/20020217
      20020223/20020224

      */


      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <set>
      #include <algorithm>
      #include <iostream>

      typedef std::set<boost::gregorian::date_period> date_period_set;

      //Simple population of the exclusion set
      date_period_set
      generateExclusion()
      {
	using namespace boost::gregorian;
	date_period periods_array[] = 
	  { date_period(date(2002,Feb,2), date(2002,Feb,4)),//weekend of 2nd-3rd
	    date_period(date(2002,Feb,9), date(2002,Feb,11)),
	    date_period(date(2002,Feb,16), date(2002,Feb,18)),
	    date_period(date(2002,Feb,23), date(2002,Feb,25)),
	    date_period(date(2002,Feb,12), date(2002,Feb,13))//a random holiday 2-12
	  };
	const int num_periods = sizeof(periods_array)/sizeof(date_period);

	date_period_set ps;
	//insert the periods in the set
	std::insert_iterator<date_period_set> itr(ps, ps.begin());
	std::copy(periods_array, periods_array+num_periods, itr );
	return ps;
	
      }


      int main() 
      {
	using namespace boost::gregorian;
	
	date_period_set ps = generateExclusion();
	std::cout << "Number Excluded Periods: "  << ps.size() << std::endl;

	date d(2002,Feb,16);
	date_period_set::const_iterator i = ps.begin();
	//print the periods, check for containment
	for (;i != ps.end(); i++) {
	  std::cout << to_iso_string(*i) << std::endl;
	  //if date is in exclusion period then print it
	  if (i->contains(d)) {
	    std::cout << "In Exclusion Period: "
		<< to_iso_string(d) << " --> " << to_iso_string(*i)
		<< std::endl;
	  }
	}

	return 0;  

      }

top

Print Holidays
This is an example of using functors to define a holiday schedule

    

      /* Generate a set of dates using a collection of date generators
       * Output looks like:
       * Enter Year: 2002
       * 2002-Jan-01 [Tue]
       * 2002-Jan-21 [Mon]
       * 2002-Feb-12 [Tue]
       * 2002-Jul-04 [Thu]
       * 2002-Sep-02 [Mon]
       * 2002-Nov-28 [Thu]
       * 2002-Dec-25 [Wed]
       * Number Holidays: 7
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <algorithm>
      #include <functional>
      #include <vector>
      #include <iostream>
      #include <set>

      void
      print_date(boost::gregorian::date d) 
      {
	using namespace boost::gregorian;
      #if defined(BOOST_DATE_TIME_NO_LOCALE)
	std::cout << to_simple_string(d) << " [" << d.day_of_week() << "]\n";
      #else
	std::cout << d << " [" << d.day_of_week() << "]\n";
      #endif
      }


      int
      main() {

	std::cout << "Enter Year: ";
	int year;
	std::cin >> year;

	using namespace boost::gregorian;

	//define a collection of holidays fixed by month and day
	std::vector<year_based_generator*> holidays;
	holidays.push_back(new partial_date(1,Jan)); //Western New Year
	holidays.push_back(new partial_date(4,Jul)); //US Independence Day
	holidays.push_back(new partial_date(25, Dec));//Christmas day


	//define a shorthand for the nth_day_of_the_week_in_month function object
	typedef nth_day_of_the_week_in_month nth_dow;
	
	//US labor day
	holidays.push_back(new nth_dow(nth_dow::first,  Monday,   Sep)); 
	//MLK Day
	holidays.push_back(new nth_dow(nth_dow::third,  Monday,   Jan)); 
	//Pres day
	holidays.push_back(new nth_dow(nth_dow::second, Tuesday,  Feb)); 
	//Thanksgiving
	holidays.push_back(new nth_dow(nth_dow::fourth, Thursday, Nov)); 

	typedef std::set<date> date_set;
	date_set all_holidays;
	
	for(std::vector<year_based_generator*>::iterator it = holidays.begin();
	    it != holidays.end(); ++it)
	{
	  all_holidays.insert((*it)->get_date(year));
	}

	//print the holidays to the screen
	std::for_each(all_holidays.begin(), all_holidays.end(), print_date);
	std::cout << "Number Holidays: " << all_holidays.size() << std::endl;

	return 0;
      }

top

Print Month
Simple utility to print out days of the month with the days of a month. Demontstrates date iteration (date_time::date_itr).

    
      /* This example prints all the dates in a month. It demonstrates
       * the use of iterators as well as functions of the gregorian_calendar
       * 
       * Output:
       * Enter Year: 2002
       * Enter Month(1..12): 2
       * 2002-Feb-01 [Fri]
       * 2002-Feb-02 [Sat]
       * 2002-Feb-03 [Sun]
       * 2002-Feb-04 [Mon]
       * 2002-Feb-05 [Tue]
       * 2002-Feb-06 [Wed]
       * 2002-Feb-07 [Thu]
       */

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

      int
      main()
      {
	std::cout << "Enter Year: ";
	int year, month;
	std::cin >> year;
	std::cout << "Enter Month(1..12): ";
	std::cin >> month;

	using namespace boost::gregorian;
	try {
	  //Use the calendar to get the last day of the month
	  int eom_day = gregorian_calendar::end_of_month_day(year,month);
	  date endOfMonth(year,month,eom_day);

	  //construct an iterator starting with firt day of the month
	  day_iterator ditr(date(year,month,1));
	  //loop thru the days and print each one
	  for (; ditr <= endOfMonth; ++ditr) {
      #if defined(BOOST_DATE_TIME_NO_LOCALE) 
	    std::cout << to_simple_string(*ditr) << " ["
      #else
	    std::cout << *ditr << " ["
      #endif
		      << ditr->day_of_week() << "]"
		      << std::endl; 
	  }
	}
	catch(std::exception& e) {

	  std::cout << "Error bad date, check your entry: \n"
		    << "  Details: " << e.what() << std::endl;
	}
	return 0;
      }

top

Month Adding
Adding a month to a day without the use of iterators.

    
      /* Simple program that uses the gregorian calendar to progress by exactly
       * one month, irregardless of how many days are in that month.
       *
       * This method can be used as an alternative to iterators
       */

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

      int
      main()
      {

	using namespace boost::gregorian;
	typedef boost::date_time::month_functor<date> add_month;

	date d = day_clock::local_day();
	add_month mf(1);
	date d2 = d + mf.get_offset(d);
	std::cout << "Today is: " << to_simple_string(d) << ".\n"
	  << "One month from today will be: " << to_simple_string(d2) 
	  << std::endl;

	return 0;
      }

top

Time Math
Various types of calculations with times and time durations.

    
      /* Some simple examples of constructing and calculating with times
       * Output:
       * 2002-Feb-01 00:00:00 - 2002-Feb-01 05:04:02.001000000 = -5:04:02.001000000
       */

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

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	date d(2002,Feb,1); //an arbitrary date
	//construct a time by adding up some durations durations
	ptime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1));
	//construct a new time by subtracting some times
	ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);
	//construct a duration by taking the difference between times
	time_duration td = t2 - t1;
	  
	std::cout << to_simple_string(t2) << " - " 
		  << to_simple_string(t1) << " = "
		  << to_simple_string(td) << std::endl;
	
	return 0;
      }

top

Print Hours
Demonstrate time iteration, clock retrieval, and simple calculation.

    
      /* Print the remaining hours of the day
       * Uses the clock to get the local time 
       * Use an iterator to iterate over the remaining hours
       * Retrieve the date part from a time
       *
       * Expected Output something like:
       *
       * 2002-Mar-08 16:30:59
       * 2002-Mar-08 17:30:59
       * 2002-Mar-08 18:30:59
       * 2002-Mar-08 19:30:59
       * 2002-Mar-08 20:30:59
       * 2002-Mar-08 21:30:59
       * 2002-Mar-08 22:30:59
       * 2002-Mar-08 23:30:59
       * Time left till midnight: 07:29:01
       */

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

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	//get the current time from the clock -- one second resolution
	ptime now = second_clock::local_time();
	//Get the date part out of the time
	date today = now.date();
	date tommorrow = today + days(1);
	ptime tommorrow_start(tommorrow); //midnight 

	//iterator adds by one hour
	time_iterator titr(now,hours(1)); 
	for (; titr < tommorrow_start; ++titr) {
	  std::cout << to_simple_string(*titr) << std::endl;
	}
	
	time_duration remaining = tommorrow_start - now;
	std::cout << "Time left till midnight: " 
		  << to_simple_string(remaining) << std::endl;
	return 0;
      }

top

Local to UTC Conversion
Demonstrate utc to local and local to utc calculations including dst.

    

      /* Demonstrate conversions between a local time and utc
       * Output:
       * 
       * UTC <--> New York while DST is NOT active (5 hours)
       * 2001-Dec-31 19:00:00 in New York is 2002-Jan-01 00:00:00 UTC time 
       * 2002-Jan-01 00:00:00 UTC is 2001-Dec-31 19:00:00 New York time 
       * 
       * UTC <--> New York while DST is active (4 hours)
       * 2002-May-31 20:00:00 in New York is 2002-Jun-01 00:00:00 UTC time 
       * 2002-Jun-01 00:00:00 UTC is 2002-May-31 20:00:00 New York time 
       * 
       * UTC <--> Arizona (7 hours)
       * 2002-May-31 17:00:00 in Arizona is 2002-Jun-01 00:00:00 UTC time 
       */

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

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	//This local adjustor depends on the machine TZ settings-- highly dangerous!
	typedef boost::date_time::c_local_adjustor<ptime> local_adj;
	ptime t10(date(2002,Jan,1), hours(7)); 
	ptime t11 = local_adj::utc_to_local(t10);
	std::cout << "UTC <--> Zone base on TZ setting" << std::endl;
	std::cout << to_simple_string(t11) << " in your TZ is " 
		  << to_simple_string(t10) << " UTC time "
		  << std::endl;
	time_duration td = t11 - t10;
	std::cout << "A difference of: " 
		  << to_simple_string(td) << std::endl;


	//eastern timezone is utc-5
	typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;

	ptime t1(date(2001,Dec,31), hours(19)); //5 hours b/f midnight NY time

	std::cout << "\nUTC <--> New York while DST is NOT active (5 hours)" 
		  << std::endl;
	ptime t2 =  us_eastern::local_to_utc(t1);
	std::cout << to_simple_string(t1) << " in New York is " 
		  << to_simple_string(t2) << " UTC time "
		  << std::endl;

	ptime t3 = us_eastern::utc_to_local(t2);//back should be the same
	std::cout << to_simple_string(t2) << " UTC is " 
		  << to_simple_string(t3) << " New York time "
		  << "\n\n";

	ptime t4(date(2002,May,31), hours(20)); //4 hours b/f midnight NY time
	std::cout << "UTC <--> New York while DST is active (4 hours)" << std::endl;
	ptime t5 = us_eastern::local_to_utc(t4);
	std::cout << to_simple_string(t4) << " in New York is " 
		  << to_simple_string(t5) << " UTC time "
		  << std::endl;

	ptime t6 = us_eastern::utc_to_local(t5);//back should be the same
	std::cout << to_simple_string(t5) << " UTC is " 
		  << to_simple_string(t6) << " New York time "
		  << "\n" << std::endl;

	  
	//Arizona timezone is utc-7 with no dst
	typedef boost::date_time::local_adjustor<ptime, -7, no_dst> us_arizona;

	ptime t7(date(2002,May,31), hours(17)); 
	std::cout << "UTC <--> Arizona (7 hours)" << std::endl;
	ptime t8 = us_arizona::local_to_utc(t7);
	std::cout << to_simple_string(t7) << " in Arizona is " 
		  << to_simple_string(t8) << " UTC time "
		  << std::endl;

	return 0;
      }

top

Time Periods
Demonstrate some simple uses of time periods.

    

      /* Some simple examples of constructing and calculating with times
       * Returns:
       * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] contains 2002-Feb-01 03:00:05
       * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] intersected with
       * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999] is 
       * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999]
       */

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

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

      //Create a simple period class to contain all the times in a day
      class day_period : public time_period
      {
      public:
	day_period(date d) : time_period(ptime(d),//midnight
					 ptime(d,hours(24)))
	{}

      };

      int
      main() 
      {

	date d(2002,Feb,1); //an arbitrary date
	//a period that represents a day  
	day_period dp(d);
	ptime t(d, hours(3)+seconds(5)); //an arbitray time on that day
	if (dp.contains(t)) {
	  std::cout << to_simple_string(dp) << " contains "
		    << to_simple_string(t)  << std::endl;
	}
	//a period that represents part of the day
	time_period part_of_day(ptime(d, hours(0)), t);
	//intersect the 2 periods and print the results
	if (part_of_day.intersects(dp)) {
	  time_period result = part_of_day.intersection(dp);
	  std::cout << to_simple_string(dp) << " intersected with\n"
		    << to_simple_string(part_of_day) << " is \n"
		    << to_simple_string(result) << std::endl;
	}
	  
	
	return 0;
      }

top