The Boost C++ LibrariesThe Boost C++ Libraries Documentation for some libraries is available in alternative formats: HTML (tarred, gzipped)PDFUnix man pagesDocBookXSL Formatting Objects
Libraries Listed AlphabeticallyAny - Safe, generic container for single values of different value types , from Kevlin Henney.Array - STL compliant container wrapper for arrays of constant size, from Nicolai Josuttis.Bind - Generalized binders for function/object/pointers and member functions, from Peter Dimov.CRC - Cyclic Redundancy Code, from Daryle Walker.Call Traits - Defines types for passing parameters, from John Maddock and Howard Hinnant.Compatibility - Help for non-conforming standard libraries, from Ralf Grosse-Kunstleve and Jens Maurer.Compose - Functional composition adapters for the STL, from Nicolai Josuttis.Compressed Pair - Empty member optimization, from John Maddock and Howard Hinnant.Concept Check - Tools for generic programming, from Jeremy Siek.Config - Helps boost library developers adapt to compiler idiosyncrasies; not intended for library users, from John Maddock, Beman Dawes, and Vesa Karvonen.Conversion - Numeric, polymorphic, and lexical casts, from Dave Abrahams and Kevlin Henney.Date Time - A set of facilities to ease programming with dates and times. , from Jeff Garland.Dynamic Bitset - A runtime sized version of std::bitset, from Jeremy Siek and Chuck Allison.Filesystem - Portable paths, iteration over directories, and other useful filesystem operations, from Beman Dawes.Format - Type-safe 'printf-like' format operations, from Samuel Krempp.Function - Function object wrappers for deferred calls or callbacks, from Douglas Gregor.Functional - Enhanced function object adaptors, from Mark Rodgers.Graph - Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.I/O State Savers - Save I/O state to prevent jumbled data, from Daryle Walker.Integer - Headers to ease dealing with integral types, from various authors.Interval - Extends the usual arithmetic functions to mathematical intervals, from Guillaume Melquiond, Hervé Brönnimann, and Sylvain Pion.Iterator Adaptors - Adapt a base type into a standard conforming iterator, from Dave Abrahams, Jeremy Siek, and John Potter.Lambda - Define small unnamed function objects at the actual call site, and more, from Jaakko Järvi.MPL - Template metaprogramming framework of compile-time algorithms, sequences and metafunction classes, from Aleksey Gurtovoy.Math - Several contributions in the domain of mathematics, from various authors.Math/Common Factor - Greatest common divisor and least common multiple, from Daryle Walker.Math/Octonion - Octonions, from Hubert Holin.Math/Quaternion - Quaternions, from Hubert Holin.Math/Special Functions - Mathematical special functions such as atanh, sinc, and sinhc, from Hubert Holin.Mem_fn - Generalized binders for member functions, from Peter Dimov.Multi Array - Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.Operators - Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.Optional - Discriminated-union wrapper for optional values, from Fernando Cacciola.Pool - Memory pool management, from Steve Cleary.Preprocessor - Preprocessor metaprogramming tools including repetition and recursion, from Vesa Karvonen and Paul Mensonides.Program_options - Facilities to obtain configuration data from command line, config files and other sources, from Vladimir Prus.Property Map - Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.Python - Reflects C++ classes and functions into Python, from Dave Abrahams.Random - A complete system for random number generation, from Jens Maurer.Rational - A rational number class, from Paul Moore.Ref - A utility library for passing references to generic functions, from Jaakko Järvi, Peter Dimov, Douglas Gregor, and Dave Abrahams.Regex - Regular expression library, from John Maddock.Serialization - Serialization of C++ objects for persistence and marshalling, from Robert Ramey.Signals - Managed signals & slots callback implementation, from Douglas Gregor.Smart Pointer - Five smart pointer class templates, from Greg Colvin, Beman Dawes, Peter Dimov, and Darin Adler.Spirit - LL parser framework represents parsers directly as EBNF grammars in inlined C++, from Joel de Guzman and team .Static Assert - Static assertions (compile time assertions), from John Maddock.String Algorithms - A set of generic string-related algorithms and utilities , from Pavol Droba.Test - Support for simple program testing, full unit testing, and for program execution monitoring, from Gennadiy Rozental.Threads - Portable C++ multi-threading, from William Kempf.Timer - Event timer, progress timer, and progress display classes, from Beman Dawes.Tokenizer - Break of a string or other character sequence into a series of tokens, from John Bandela.Tribool - Three-state boolean type, from Douglas Gregor.Tuple - Ease definition of functions returning multiple values, and more, from Jaakko Järvi.Type Traits - Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .Utility - Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .Variant - Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.uBLAS - Basic linear algebra for dense, packed and sparse matrices, from Joerg Walter and Mathias Koch.
Libraries Listed by Category
String and text processing Format - Type-safe 'printf-like' format operations, from Samuel Krempp.Regex - Regular expression library, from John Maddock.String Algorithms - A set of generic string-related algorithms and utilities , from Pavol Droba.Tokenizer - Break of a string or other character sequence into a series of tokens, from John Bandela.
Containers Array - STL compliant container wrapper for arrays of constant size, from Nicolai Josuttis.Dynamic Bitset - A runtime sized version of std::bitset, from Jeremy Siek and Chuck Allison.Graph - Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.Multi Array - Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.Property Map - Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.Variant - Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.
Iterators Graph - Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.Iterator Adaptors - Adapt a base type into a standard conforming iterator, from Dave Abrahams, Jeremy Siek, and John Potter.Operators - Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.Tokenizer - Break of a string or other character sequence into a series of tokens, from John Bandela.
Algorithms Graph - Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.Utility - Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Function objects and higher-order programming Bind - Generalized binders for function/object/pointers and member functions, from Peter Dimov.Compose - Functional composition adapters for the STL, from Nicolai Josuttis.Function - Function object wrappers for deferred calls or callbacks, from Douglas Gregor.Functional - Enhanced function object adaptors, from Mark Rodgers.Lambda - Define small unnamed function objects at the actual call site, and more, from Jaakko Järvi.Mem_fn - Generalized binders for member functions, from Peter Dimov.Ref - A utility library for passing references to generic functions, from Jaakko Järvi, Peter Dimov, Douglas Gregor, and Dave Abrahams.Signals - Managed signals & slots callback implementation, from Douglas Gregor.
Generic programming Call Traits - Defines types for passing parameters, from John Maddock and Howard Hinnant.Concept Check - Tools for generic programming, from Jeremy Siek.Operators - Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.Property Map - Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.Static Assert - Static assertions (compile time assertions), from John Maddock.Type Traits - Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .
Template metaprogramming MPL - Template metaprogramming framework of compile-time algorithms, sequences and metafunction classes, from Aleksey Gurtovoy.Static Assert - Static assertions (compile time assertions), from John Maddock.Type Traits - Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .
Preprocessor metaprogramming Preprocessor - Preprocessor metaprogramming tools including repetition and recursion, from Vesa Karvonen and Paul Mensonides.
Concurrent programming Threads - Portable C++ multi-threading, from William Kempf.
Math and numerics Integer - Headers to ease dealing with integral types, from various authors.Interval - Extends the usual arithmetic functions to mathematical intervals, from Guillaume Melquiond, Hervé Brönnimann, and Sylvain Pion.Math - Several contributions in the domain of mathematics, from various authors.Math/Common Factor - Greatest common divisor and least common multiple, from Daryle Walker.Math/Octonion - Octonions, from Hubert Holin.Math/Quaternion - Quaternions, from Hubert Holin.Math/Special Functions - Mathematical special functions such as atanh, sinc, and sinhc, from Hubert Holin.Multi Array - Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.Operators - Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.Random - A complete system for random number generation, from Jens Maurer.Rational - A rational number class, from Paul Moore.uBLAS - Basic linear algebra for dense, packed and sparse matrices, from Joerg Walter and Mathias Koch.
Correctness and testing Concept Check - Tools for generic programming, from Jeremy Siek.Static Assert - Static assertions (compile time assertions), from John Maddock.Test - Support for simple program testing, full unit testing, and for program execution monitoring, from Gennadiy Rozental.
Data structures Any - Safe, generic container for single values of different value types , from Kevlin Henney.Compressed Pair - Empty member optimization, from John Maddock and Howard Hinnant.Optional - Discriminated-union wrapper for optional values, from Fernando Cacciola.Program_options - Facilities to obtain configuration data from command line, config files and other sources, from Vladimir Prus.Tuple - Ease definition of functions returning multiple values, and more, from Jaakko Järvi.Variant - Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.
Input/Output Format - Type-safe 'printf-like' format operations, from Samuel Krempp.I/O State Savers - Save I/O state to prevent jumbled data, from Daryle Walker.Serialization - Serialization of C++ objects for persistence and marshalling, from Robert Ramey.
Inter-language support Python - Reflects C++ classes and functions into Python, from Dave Abrahams.
Memory Pool - Memory pool management, from Steve Cleary.Smart Pointer - Five smart pointer class templates, from Greg Colvin, Beman Dawes, Peter Dimov, and Darin Adler.Utility - Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Parsing Spirit - LL parser framework represents parsers directly as EBNF grammars in inlined C++, from Joel de Guzman and team .
Miscellaneous CRC - Cyclic Redundancy Code, from Daryle Walker.Compressed Pair - Empty member optimization, from John Maddock and Howard Hinnant.Conversion - Numeric, polymorphic, and lexical casts, from Dave Abrahams and Kevlin Henney.Date Time - A set of facilities to ease programming with dates and times. , from Jeff Garland.Filesystem - Portable paths, iteration over directories, and other useful filesystem operations, from Beman Dawes.Optional - Discriminated-union wrapper for optional values, from Fernando Cacciola.Timer - Event timer, progress timer, and progress display classes, from Beman Dawes.Tribool - Three-state boolean type, from Douglas Gregor.Utility - Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Broken compiler workarounds Compatibility - Help for non-conforming standard libraries, from Ralf Grosse-Kunstleve and Jens Maurer.Config - Helps boost library developers adapt to compiler idiosyncrasies; not intended for library users, from John Maddock, Beman Dawes, and Vesa Karvonen.
KevlinHenney2001Kevlin HenneyBoost.Any
IntroductionThere are times when a generic (in the sense of general as opposed to template-based programming) type is needed: variables that are truly variable, accommodating values of many other more specific types rather than C++'s normal strict and static types. We can distinguish three basic kinds of generic type:Converting types that can hold one of a number of possible value types, e.g. int and string, and freely convert between them, for instance interpreting 5 as "5" or vice-versa. Such types are common in scripting and other interpreted languages. boost::lexical_cast supports such conversion functionality. Discriminated types that contain values of different types but do not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions. Indiscriminate types that can refer to anything but are oblivious to the actual underlying type, entrusting all forms of access and interpretation to the programmer. This niche is dominated by void *, which offers plenty of scope for surprising, undefined behavior.The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type. A similar design, offering more appropriate operators, can be used for a generalized function adaptor, any_function, a generalized iterator adaptor, any_iterator, and other object types that need uniform runtime treatment but support only compile-time template parameter conformance.
ExamplesThe following code demonstrates the syntax for using implicit conversions to and copying of any objects: #include <list> #include <boost/any.hpp> using boost::any_cast; typedef std::list<boost::any> many; void append_int(many & values, int value) { boost::any to_append = value; values.push_back(to_append); } void append_string(many & values, const std::string & value) { values.push_back(value); } void append_char_ptr(many & values, const char * value) { values.push_back(value); } void append_any(many & values, const boost::any & value) { values.push_back(value); } void append_nothing(many & values) { values.push_back(boost::any()); } The following predicates follow on from the previous definitions and demonstrate the use of queries on any objects: bool is_empty(const boost::any & operand) { return operand.empty(); } bool is_int(const boost::any & operand) { return operand.type() == typeid(int); } bool is_char_ptr(const boost::any & operand) { try { any_cast<const char *>(operand); return true; } catch(const boost::bad_any_cast &) { return false; } } bool is_string(const boost::any & operand) { return any_cast<std::string>(&operand); } void count_all(many & values, std::ostream & out) { out << "#empty == " << std::count_if(values.begin(), values.end(), is_empty) << std::endl; out << "#int == " << std::count_if(values.begin(), values.end(), is_int) << std::endl; out << "#const char * == " << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl; out << "#string == " << std::count_if(values.begin(), values.end(), is_string) << std::endl; } The following type, patterned after the OMG's Property Service, defines name-value pairs for arbitrary value types: struct property { property(); property(const std::string &, const boost::any &); std::string name; boost::any value; }; typedef std::list<property> properties; The following base class demonstrates one approach to runtime polymorphism based callbacks that also require arbitrary argument types. The absence of virtual member templates requires that different solutions have different trade-offs in terms of efficiency, safety, and generality. Using a checked variant type offers one approach: class consumer { public: virtual void notify(const any &) = 0; ... };
Reference
<emphasis>ValueType</emphasis> requirementsValues are strongly informational objects for which identity is not significant, i.e. the focus is principally on their state content and any behavior organized around that. Another distinguishing feature of values is their granularity: normally fine-grained objects representing simple concepts in the system such as quantities.As the emphasis of a value lies in its state not its identity, values can be copied and typically assigned one to another, requiring the explicit or implicit definition of a public copy constructor and public assignment operator. Values typically live within other scopes, i.e. within objects or blocks, rather than on the heap. Values are therefore normally passed around and manipulated directly as variables or through references, but not as pointers that emphasize identity and indirection.The specific requirements on value types to be used in an any are:A ValueType is CopyConstructible [20.1.3].A ValueType is optionally Assignable [23.1]. The strong exception-safety guarantee is required for all forms of assignment.The destructor for a ValueType upholds the no-throw exception-safety guarantee.
Header <<ulink url="../../boost/any.hpp">boost/any.hpp</ulink>>namespace boost {   class bad_any_cast;   class any;   template<typename ValueType> ValueType any_cast(const any &);   template<typename ValueType> const ValueType * any_cast(const any *);   template<typename ValueType> ValueType * any_cast(any *); }Class bad_any_cast3boost::bad_any_castThe exception thrown in the event of a failed any_cast of an any value. class bad_any_cast : public std::bad_cast { public:   virtual const char * what() const; };Descriptionvirtual const char * what() const;Class any3boost::anyA class whose instances can hold instances of any type that satisfies ValueType requirements. class any { public:   // construct/copy/destruct   any();   any(const any &);   template<typename ValueType> any(const ValueType &);   any & operator=(const any &);   template<typename ValueType> any & operator=(const ValueType &);   ~any();   // modifiers   any & swap(any &);   // queries   bool empty() const;   const std::type_info & type() const; };Description<anchor id="boost.anyconstruct-copy-destruct"/><computeroutput>any</computeroutput> construct/copy/destructany();Postconditionsthis->empty()any(const any & other);Effects Copy constructor that copies content of other into new instance, so that any content is equivalent in both type and value to the content of other, or empty if other is empty. ThrowsMay fail with a std::bad_alloc exception or any exceptions arising from the copy constructor of the contained type.template<typename ValueType> any(const ValueType & value);EffectsMakes a copy of value, so that the initial content of the new instance is equivalent in both type and value to value.Throwsstd::bad_alloc or any exceptions arising from the copy constructor of the contained type.any & operator=(const any & rhs);EffectsCopies content of rhs into current instance, discarding previous content, so that the new content is equivalent in both type and value to the content of rhs, or empty if rhs.empty().Throwsstd::bad_alloc or any exceptions arising from the copy constructor of the contained type. Assignment satisfies the strong guarantee of exception safety.template<typename ValueType> any & operator=(const ValueType & rhs);EffectsMakes a copy of rhs, discarding previous content, so that the new content of is equivalent in both type and value to rhs.Throwsstd::bad_alloc or any exceptions arising from the copy constructor of the contained type. Assignment satisfies the strong guarantee of exception safety.~any();EffectsReleases any and all resources used in management of instance.ThrowsNothing.<anchor id="id141128-bb"/><computeroutput>any</computeroutput> modifiersany & swap(any & rhs);EffectsExchange of the contents of *this and rhs.Returns*thisThrowsNothing.<anchor id="id141177-bb"/><computeroutput>any</computeroutput> queriesbool empty() const;Returnstrue if instance is empty, otherwise false.ThrowsWill not throw.const std::type_info & type() const;Returnsthe typeid of the contained value if instance is non-empty, otherwise typeid(void).NotesUseful for querying against types known either at compile time or only at runtime.Function any_cast3boost::any_castCustom keyword cast for extracting a value of a given type from an any. template<typename ValueType> ValueType any_cast(const any & operand); template<typename ValueType> const ValueType * any_cast(const any * operand); template<typename ValueType> ValueType * any_cast(any * operand);DescriptionReturns If passed a pointer, it returns a similarly qualified pointer to the value content if successful, otherwise null is returned. If passed a value or reference, it returns a copy of the value content if successful.ThrowsOverloads taking an any pointer do not throw; the overload taking an any value or reference throws bad_any_cast if unsuccessful.RationaleThe value/reference version returns a copy because the C++ keyword casts return copies.
AcknowledgementsDoug Gregor ported the documentation to the BoostBook format.
NicolaiJosuttis2001200220032004Nicolai M. JosuttisPermission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.Boost.Array
IntroductionThe C++ Standard Template Library STL as part of the C++ Standard Library provides a framework for processing algorithms on different kind of containers. However, ordinary arrays don't provide the interface of STL containers (although, they provide the iterator interface of STL containers).As replacement for ordinary arrays, the STL provides class std::vector. However, std::vector<> provides the semantics of dynamic arrays. Thus, it manages data to be able to change the number of elements. This results in some overhead in case only arrays with static size are needed.In his book, Generic Programming and the STL, Matthew H. Austern introduces a useful wrapper class for ordinary arrays with static size, called block. It is safer and has no worse performance than ordinary arrays. In The C++ Programming Language, 3rd edition, Bjarne Stroustrup introduces a similar class, called c_array, which I (Nicolai Josuttis) present slightly modified in my book The C++ Standard Library - A Tutorial and Reference, called carray. This is the essence of these approaches spiced with many feedback from boost.After considering different names, we decided to name this class simply array.Note that this class is suggested to be part of the next Technical Report, which will extend the C++ Standard (see http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1548.htm).Class array fulfills most but not all of the requirements of "reversible containers" (see Section 23.1, [lib.container.requirements] of the C++ Standard). The reasons array is not an reversible STL container is because: No constructors are provided.Elements may have an undetermined initial value (see ).swap() has no constant complexity.size() is always constant, based on the second template argument of the type.The container provides no allocator support.It doesn't fulfill the requirements of a "sequence" (see Section 23.1.1, [lib.sequence.reqmts] of the C++ Standard), except that: front() and back() are provided.operator[] and at() are provided.
Reference
Header <<ulink url="../../boost/array.hpp">boost/array.hpp</ulink>>namespace boost {   template<typename T, std::size_t N> class array;   template<typename T, std::size_t N> void swap(array<T, N>&, array<T, N>&);   template<typename T, std::size_t N>     bool operator==(const array<T, N>&, const array<T, N>&);   template<typename T, std::size_t N>     bool operator!=(const array<T, N>&, const array<T, N>&);   template<typename T, std::size_t N>     bool operator<(const array<T, N>&, const array<T, N>&);   template<typename T, std::size_t N>     bool operator>(const array<T, N>&, const array<T, N>&);   template<typename T, std::size_t N>     bool operator<=(const array<T, N>&, const array<T, N>&);   template<typename T, std::size_t N>     bool operator>=(const array<T, N>&, const array<T, N>&); }Class template array3boost::arraySTL compliant container wrapper for arrays of constant sizetemplate<typename T, std::size_t N> class array { public:   // types   typedef T                                     value_type;               typedef T*                                    iterator;                 typedef const T*                              const_iterator;           typedef std::reverse_iterator<iterator>       reverse_iterator;         typedef std::reverse_iterator<const_iterator> const_reverse_iterator;   typedef T&                                    reference;                typedef const T&                              const_reference;          typedef std::size_t                           size_type;                typedef std::ptrdiff_t                        difference_type;          // static constants   static const size_type static_size = N;   // construct/copy/destruct   template<typename U> array& operator=(const array<U, N>&);   // iterator support   iterator begin();   const_iterator begin() const;   iterator end();   const_iterator end() const;   // reverse iterator support   reverse_iterator rbegin();   const_reverse_iterator rbegin() const;   reverse_iterator rend();   const_reverse_iterator rend() const;   // capacity   size_type size();   bool empty();   size_type max_size();   // element access   reference operator[](size_type);   const_reference operator[](size_type) const;   reference at(size_type);   const_reference at(size_type) const;   reference front();   const_reference front() const;   reference back();   const_reference back() const;   const T* data() const;   T* c_array();   // modifiers   void swap(array<T, N>&);   void assign(const T&);   T elems[N]; }; // specialized algorithms template<typename T, std::size_t N> void swap(array<T, N>&, array<T, N>&); // comparisons template<typename T, std::size_t N>   bool operator==(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N>   bool operator!=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N>   bool operator<(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N>   bool operator>(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N>   bool operator<=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N>   bool operator>=(const array<T, N>&, const array<T, N>&);Description<anchor id="boost.arrayconstruct-copy-destruct"/><computeroutput>array</computeroutput> construct/copy/destructtemplate<typename U> array& operator=(const array<U, N>& other);Effectsstd::copy(rhs.begin(),rhs.end(), begin())<anchor id="id229808-bb"/><computeroutput>array</computeroutput> iterator supportiterator begin(); const_iterator begin() const;Returnsiterator for the first elementThrowswill not throwiterator end(); const_iterator end() const;Returnsiterator for position after the last elementThrowswill not throw<anchor id="id229873-bb"/><computeroutput>array</computeroutput> reverse iterator supportreverse_iterator rbegin(); const_reverse_iterator rbegin() const;Returnsreverse iterator for the first element of reverse iterationreverse_iterator rend(); const_reverse_iterator rend() const;Returnsreverse iterator for position after the last element in reverse iteration<anchor id="id229930-bb"/><computeroutput>array</computeroutput> capacitysize_type size();ReturnsNbool empty();ReturnsN==0Throwswill not throwsize_type max_size();ReturnsNThrowswill not throw<anchor id="id227251-bb"/><computeroutput>array</computeroutput> element accessreference operator[](size_type i); const_reference operator[](size_type i) const;Requiresi < NReturnselement with index iThrowswill not throw.reference at(size_type i); const_reference at(size_type i) const;Returnselement with index iThrowsstd::range_error if i >= Nreference front(); const_reference front() const;RequiresN > 0Returnsthe first elementThrowswill not throwreference back(); const_reference back() const;RequiresN > 0Returnsthe last elementThrowswill not throwconst T* data() const;ReturnselemsThrowswill not throwT* c_array();ReturnselemsThrowswill not throw<anchor id="id227478-bb"/><computeroutput>array</computeroutput> modifiersvoid swap(array<T, N>& other);Effectsstd::swap_ranges(begin(), end(), other.begin())Complexitylinear in Nvoid assign(const T& value);Effectsstd::fill_n(begin(), N, value)<anchor id="id227563-bb"/><computeroutput>array</computeroutput> specialized algorithmstemplate<typename T, std::size_t N> void swap(array<T, N>& x, array<T, N>& y);Effectsx.swap(y)Throwswill not throw.<anchor id="id287136-bb"/><computeroutput>array</computeroutput> comparisonstemplate<typename T, std::size_t N>   bool operator==(const array<T, N>& x, const array<T, N>& y);Returnsstd::equal(x.begin(), x.end(), y.begin())template<typename T, std::size_t N>   bool operator!=(const array<T, N>& x, const array<T, N>& y);Returns!(x == y)template<typename T, std::size_t N>   bool operator<(const array<T, N>& x, const array<T, N>& y);Returnsstd::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end())template<typename T, std::size_t N>   bool operator>(const array<T, N>& x, const array<T, N>& y);Returnsy < xtemplate<typename T, std::size_t N>   bool operator<=(const array<T, N>& x, const array<T, N>& y);Returns!(y < x)template<typename T, std::size_t N>   bool operator>=(const array<T, N>& x, const array<T, N>& y);Returns!(x < y)
Design RationaleThere was an important design tradeoff regarding the constructors: We could implement array as an "aggregate" (see Section 8.5.1, [dcl.init.aggr], of the C++ Standard). This would mean: An array can be initialized with a brace-enclosing, comma-separated list of initializers for the elements of the container, written in increasing subscript order:boost::array<int,4> a = { { 1, 2, 3 } };Note that if there are fewer elements in the initializer list, then each remaining element gets default-initialized (thus, it has a defined value).However, this approach has its drawbacks: passing no initializer list means that the elements have an indetermined initial value, because the rule says that aggregates may have: No user-declared constructors.No private or protected non-static data members.No base classes.No virtual functions.Nevertheless, The current implementation uses this approach.Note that for standard conforming compilers it is possible to use fewer braces (according to 8.5.1 (11) of the Standard). That is, you can initialize an array as follows:boost::array<int,4> a = { 1, 2, 3 }; I'd appreciate any constructive feedback. Please note: I don't have time to read all boost mails. Thus, to make sure that feedback arrives to me, please send me a copy of each mail regarding this class.The code is provided "as is" without expressed or implied warranty.
For more information...To find more details about using ordinary arrays in C++ and the framework of the STL, see e.g. The C++ Standard Library - A Tutorial and Reference by Nicolai M. Josuttis Addison Wesley Longman, 1999 ISBN 0-201-37926-0Home Page of Nicolai Josuttis
AcknowledgementsDoug Gregor ported the documentation to the BoostBook format.
ConceptsAssignableInputIteratorOutputIteratorForwardIteratorBidirectionalIteratorRandomAccessIteratorDefaultConstructibleCopyConstructibleEqualityComparableLessThanComparableSignedInteger
20012002Indiana University20002001University of Notre Dame du Lac2000Jeremy SiekLie-Quan LeeAndrew Lumsdaine1996199719981999Silicon Graphics Computer Systems, Inc.1994Hewlett-Packard CompanyThis product includes software developed at the University of Notre Dame and the Pervasive Technology Labs at Indiana University. For technical information contact Andrew Lumsdaine at the Pervasive Technology Labs at Indiana University. For administrative and license questions contact the Advanced Research and Technology Institute at 351 West 10th Street. Indianapolis, Indiana 46202, phone 317-278-4100, fax 317-274-5902.Some concepts based on versions from the MTL draft manual and Boost Graph and Property Map documentation, the SGI Standard Template Library documentation and the Hewlett-Packard STL, under the following license:
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appears in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Silicon Graphics makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
Concept referenceConcept Assignable7AssignableDescriptionAssignable types must have copy constructors, operator= for assignment, and the swap() function defined.Refinement ofCopyConstructibleNotationXA type playing the role of assignable-type in the Assignable concept.xyObjects of type XValid expressionsNameExpressionTypeSemanticsAssignmentx = yX &Require operator=Swapswap(x, y)voidRequire swap() functionModelsintSee alsoCopyConstructibleConcept InputIterator7InputIteratorDescriptionAn input iterator is an iterator that can read through a sequence of values. It is single-pass (old values of the iterator cannot be re-used), and read-only.An input iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).Refinement ofAssignableDefaultConstructibleEqualityComparableAssociated typesvalue_typestd::iterator_traits<Iter>::value_typeThe value type of the iterator (not necessarily what *i returns)difference_typestd::iterator_traits<Iter>::difference_typeThe difference type of the iteratorcategorystd::iterator_traits<Iter>::iterator_categoryThe category of the iteratorNotationIterA type playing the role of iterator-type in the InputIterator concept.ijObjects of type IterxObject of type value_typeType expressionsCategory tagcategory must be derived from std::input_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible. Value type copy constructibilityvalue_type must be a model of CopyConstructible. Difference type propertiesdifference_type must be a model of SignedInteger. Valid expressionsNameExpressionTypePreconditionSemanticsPostconditionDereference*iConvertible to value_typei is incrementable (not off-the-end)Preincrement++iIter &i is incrementable (not off-the-end)Postincrementi++i is incrementable (not off-the-end)Equivalent to (void)(++i)i is dereferenceable or off-the-endPostincrement and dereference*i++Convertible to value_typei is incrementable (not off-the-end)Equivalent to {value_type t = *i; ++i; return t;}i is dereferenceable or off-the-endComplexity All iterator operations must take amortized constant time. Modelsstd::istream_iteratorSee alsoDefaultConstructibleEqualityComparableForwardIteratorOutputIteratorConcept OutputIterator7OutputIteratorDescriptionAn output iterator is an iterator that can write a sequence of values. It is single-pass (old values of the iterator cannot be re-used), and write-only.An output iterator represents a position in a (possibly infinite) sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).Associated typesvalue_typestd::iterator_traits<Iter>::value_typeThe stated value type of the iterator (should be void for an output iterator that does not model some other iterator concept).difference_typestd::iterator_traits<Iter>::difference_typeThe difference type of the iteratorcategorystd::iterator_traits<Iter>::iterator_categoryThe category of the iteratorNotationIterA type playing the role of iterator-type in the OutputIterator concept.ValueTypeA type playing the role of value-type in the OutputIterator concept.ijObjects of type IterxObject of type ValueTypeType expressionsThe type Iter must be a model of Assignable.The type ValueType must be a model of Assignable.The type Iter must be a model of DefaultConstructible.The type Iter must be a model of EqualityComparable.Category tagcategory must be derived from std::output_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible. Difference type propertiesdifference_type must be a model of SignedInteger. Valid expressionsNameExpressionTypePreconditionSemanticsPostconditionDereference*ii is incrementable (not off-the-end)Dereference and assign*i = xi is incrementable (not off-the-end)*i may not be written to again until it has been incremented.Preincrement++iIter &i is incrementable (not off-the-end)Postincrementi++i is incrementable (not off-the-end)Equivalent to (void)(++i)i is dereferenceable or off-the-endPostincrement, dereference, and assign*i++ = xi is incrementable (not off-the-end)Equivalent to {*i = t; ++i;}i is dereferenceable or off-the-endComplexity All iterator operations must take amortized constant time. Modelsstd::ostream_iterator...std::insert_iterator...std::front_insert_iterator...std::back_insert_iterator...See alsoConcept ForwardIterator7ForwardIteratorDescriptionA forward iterator is an iterator that can read through a sequence of values. It is multi-pass (old values of the iterator can be re-used), and can be either mutable (data pointed to by it can be changed) or not mutable.An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).Refinement ofInputIteratorOutputIteratorAssociated typesvalue_typestd::iterator_traits<Iter>::value_typeThe value type of the iteratorcategorystd::iterator_traits<Iter>::iterator_categoryThe category of the iteratorNotationIterA type playing the role of iterator-type in the ForwardIterator concept.ijObjects of type IterxObject of type value_typeType expressionsCategory tagcategory must be derived from std::forward_iterator_tag. Valid expressionsNameExpressionTypePreconditionSemanticsPostconditionDereference*iconst-if-not-mutable value_type &i is incrementable (not off-the-end)Member accessi->{member-name} (return type is pointer-to-object type)const-if-not-mutable value_type *i is incrementable (not off-the-end)Preincrement++iIter &i is incrementable (not off-the-end)Postincrementi++Iteri is incrementable (not off-the-end)Equivalent to {Iter j = i; ++i; return j;}i is dereferenceable or off-the-endComplexity All iterator operations must take amortized constant time. InvariantsPredecrement must return object&i = &(++i)Unique path through sequencei == j implies ++i == ++jModelsT *std::hash_set<T>::iteratorSee alsoBidirectionalIteratorConcept BidirectionalIterator7BidirectionalIteratorDescriptionA bidirectional iterator is an iterator that can read through a sequence of values. It can move in either direction through the sequence, and can be either mutable (data pointed to by it can be changed) or not mutable.An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).Refinement ofForwardIteratorAssociated typesvalue_typestd::iterator_traits<Iter>::value_typeThe value type of the iteratorcategorystd::iterator_traits<Iter>::iterator_categoryThe category of the iteratorNotationIterA type playing the role of iterator-type in the BidirectionalIterator concept.ijObjects of type IterxObject of type value_typeType expressionsCategory tagcategory must be derived from std::bidirectional_iterator_tag. Valid expressionsNameExpressionTypePreconditionSemanticsPostconditionPredecrement--iIter &i is incrementable (not off-the-end) and some dereferenceable iterator j exists such that i == ++jPostdecrementi--IterSame as for predecrementEquivalent to {Iter j = i; --i; return j;}i is dereferenceable or off-the-endComplexity All iterator operations must take amortized constant time. InvariantsPredecrement must return object&i = &(--i)Unique path through sequencei == j implies --i == --jIncrement and decrement are inverses++i; --i; and --i; ++i; must end up with the value of i unmodified, if i both of the operations in the pair are valid. ModelsT *std::list<T>::iteratorSee alsoRandomAccessIteratorConcept RandomAccessIterator7RandomAccessIteratorDescriptionA random access iterator is an iterator that can read through a sequence of values. It can move in either direction through the sequence (by any amount in constant time), and can be either mutable (data pointed to by it can be changed) or not mutable.An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).Refinement ofBidirectionalIteratorLessThanComparableAssociated typesvalue_typestd::iterator_traits<Iter>::value_typeThe value type of the iteratorcategorystd::iterator_traits<Iter>::iterator_categoryThe category of the iteratordifference_typestd::iterator_traits<Iter>::difference_typeThe difference type of the iterator (measure of the number of steps between two iterators)NotationIterA type playing the role of iterator-type in the RandomAccessIterator concept.ijObjects of type IterxObject of type value_typenObject of type difference_typeint_offObject of type intType expressionsCategory tagcategory must be derived from std::random_access_iterator_tag. Valid expressionsNameExpressionTypeSemanticsMotioni += nIter &Equivalent to applying i++n times if n is positive, applying i---n times if n is negative, and to a null operation if n is zero.Motion (with integer offset)i += int_offIter &Equivalent to applying i++n times if n is positive, applying i---n times if n is negative, and to a null operation if n is zero.Subtractive motioni -= nIter &Equivalent to i+=(-n)Subtractive motion (with integer offset)i -= int_offIter &Equivalent to i+=(-n)Additioni + nIterEquivalent to {Iter j = i; j += n; return j;}Addition with integeri + int_offIterEquivalent to {Iter j = i; j += n; return j;}Addition (count first)n + iIterEquivalent to i + nAddition with integer (count first)int_off + iIterEquivalent to i + nSubtractioni - nIterEquivalent to i + (-n)Subtraction with integeri - int_offIterEquivalent to i + (-n)Distancei - jdifference_typeThe number of times i must be incremented (or decremented if the result is negative) to reach j. Not defined if j is not reachable from i.Element accessi[n]const-if-not-mutable value_type &Equivalent to *(i + n)Element access with integer indexi[int_off]const-if-not-mutable value_type &Equivalent to *(i + n)Complexity All iterator operations must take amortized constant time. ModelsT *std::vector<T>::iteratorstd::vector<T>::const_iteratorstd::deque<T>::iteratorstd::deque<T>::const_iteratorSee alsoLessThanComparableConcept DefaultConstructible7DefaultConstructibleDescriptionDefaultConstructible objects only need to have a default constructor.NotationXA type playing the role of default-constructible-type in the DefaultConstructible concept.Valid expressionsNameExpressionTypeSemanticsConstructionX()XConstruct an instance of the type with default parameters.Modelsintstd::vector<double>Concept CopyConstructible7CopyConstructibleDescriptionCopy constructible types must be able to be constructed from another member of the type.NotationXA type playing the role of copy-constructible-type in the CopyConstructible concept.xyObjects of type XValid expressionsNameExpressionTypeSemanticsCopy constructionX(x)XRequire copy constructor.ModelsintConcept EqualityComparable7EqualityComparableDescriptionEquality Comparable types must have == and != operators.NotationXA type playing the role of comparable-type in the EqualityComparable concept.xyObjects of type XValid expressionsNameExpressionTypeEquality testx == yConvertible to boolInequality testx != yConvertible to boolModelsintstd::vector<int>Concept LessThanComparable7LessThanComparableDescriptionLessThanComparable types must have <, >, <=, and >= operators.NotationXA type playing the role of comparable-type in the LessThanComparable concept.xyObjects of type XValid expressionsNameExpressionTypeSemanticsLess thanx < yConvertible to boolDetermine if one value is less than another.Less than or equalx <= yConvertible to boolDetermine if one value is less than or equal to another.Greater thanx > yConvertible to boolDetermine if one value is greater than another.Greater than or equal tox >= yConvertible to boolDetermine if one value is greater than or equal to another.ModelsintConcept SignedInteger7SignedIntegerRefinement ofCopyConstructibleAssignableDefaultConstructibleEqualityComparableLessThanComparableNotationTA type playing the role of integral-type in the SignedInteger concept.xyzObjects of type TabObjects of type intType expressionsConversion to intT must be convertible to int. Valid expressionsNameExpressionTypeConversion from intT(a)TPreincrement++xT &Predecrement--xT &Postincrementx++TPostdecrementx--TSumx + yTSum with intx + aTSum-assignmentx += yT &Sum-assignment with intx += aT &Differencex - yTDifference with intx - aTProductx * yTProduct with intx * aTProduct-assignment with intx *= aT &Product with int on lefta * xTQuotientx / yTQuotient with intx / aTRight-shiftx >> yTRight-shift with intx >> aTRight-shift-assignment with intx >>= aT &Less-than comparisonx < yConvertible to boolLess-than comparison with intx < aConvertible to boolLess-than comparison with size_tx < boost::sample_value < std::size_t >()Convertible to boolGreater-than comparisonx > yConvertible to boolGreater-than comparison with intx > aConvertible to boolLess-than-or-equal comparisonx <= yConvertible to boolLess-than-or-equal comparison with intx <= aConvertible to boolGreater-than-or-equal comparisonx >= yConvertible to boolGreater-than-or-equal comparison with intx >= aConvertible to boolGreater-than-or-equal comparison with int on lefta >= xConvertible to boolEquality comparisonx == yConvertible to boolEquality comparison with intx == aConvertible to boolSee also
JeffGarland2001200220032004CrystalClear Software, IncSubject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)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 TerminologyCalculationsStability, Predictability, and ApproximationsReferences
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 PageFull Doxygen Reference Manual
GregorianGregorian Date SystemIntroduction -- Usage ExamplesIntroductionThe 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 ExamplesExampleDescriptionDays AliveDays Till New YearSimple date arithmetic. Retrieve current day from clock.Dates as stringsSimple parsing and formatting of dates from/to stringsDate Period CalculationsSee if a date is in a set of date periods (eg: is it a holiday/weekend)Print a monthSmall 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 HolidaysUses date generators to convert abstract specification into concrete set of dates.
Date ClassIntroduction -- Header -- Construction -- Construct from String -- Construct from Clock -- Accessors -- Convert to String -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampledate(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 constructordate 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_timeConstruct from StringSyntaxDescriptionExampledate 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 ClockSyntaxDescriptionExampleday_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())AccessorsSyntaxDescriptionExamplegreg_year year() constGet the year part of the date. date d(2002,Jan,10); d.year() --> 2002;greg_month month() constGet 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() constReturn 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 --> 10greg_day_of_week day_of_week() constGet the day of the week (eg: Sunday, Monday, etc. date d(2002,Jan,10); d.day() --> Thursday;bool is_infinity() constReturns true if date is either positive or negative infinity date d(pos_infin); d.is_infinity() --> true;bool is_neg_infinity() constReturns true if date is negative infinity date d(neg_infin); d.is_neg_infinity() --> true;bool is_pos_infinity() constReturns true if date is positive infinity date d(neg_infin); d.is_pos_infinity() --> true;bool is_not_a_date() constReturns true if value is not a date date d(not_a_date_time); d.is_not_a_date() --> true;long modjulian_day() constReturns the modified julian day for the date.long julian_day() constReturns the julian day for the date.int week_number() constReturns the ISO 8601 week number for the date.Convert to StringSyntaxDescriptionExamplestd::string to_simple_string(date d)To YYYY-mmm-DD string where mmm 3 char month name.2002-Jan-01std::string to_iso_string(date d)To YYYYMMDD where all components are integers.20020131std::string to_iso_extended_string(date d) To YYYY-MM-DD where all components are integers.2002-01-31OperatorsSyntaxDescriptionExampleoperator<<Stream output operator date d(2002,Jan,1) std::cout << d << std::endl; operator==, operator!=, operator>, operator< operator>=, operator<=A full complement of comparison operatorsd1 == d2, etcdate operator+(date_duration) constReturn a date adding a day offset date d(2002,Jan,1); date_duration dd(1); date d2 = d + dd; date operator-(date_duration) constReturn a date by adding a day offset date d(2002,Jan,1); date_duration dd(1); date d2 = d - dd; date_duration operator-(date) constReturn 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 -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampledate_duration(long)Create a duration count. date_duration dd(3); //3 daysAccessorsSyntaxDescriptionExamplelong days() const Get the day count.date_duration dd(3); dd.days() --> 3bool is_negative() constTrue if number of days is less than zero.date_duration dd(-1); dd.is_negative() --> truestatic date_duration unit()Return smallest possible unit of duration type.date_duration::unit() --> date_duration(1)OperatorsSyntaxDescriptionExample operator==, operator!=, operator>, operator< operator>=, operator<= A full complement of comparison operatorsdd1 == dd2, etcdate_duration operator+(date_duration) constAdd date durations. date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 + dd2; date_duration operator-(date_duration) constSubtract durations. date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 - dd2; top
Date PeriodIntroduction -- Header -- Construction -- Accessors -- Convert to String -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampledate_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)AccessorsSyntaxDescriptionExampledate 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() constReturn last date in the period date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.last() --> 2002-Jan-09 date end() constReturn 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() constReturn the length of the date_period date_period dp(date(2002,Jan,1), date_duration(2)); dp.length() --> 2 bool is_null() constTrue 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) constTrue 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) constTrue 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) constTrue 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) constCalculate 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) constCheck 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) constDetermine 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) constDetermine 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) constReturns 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) constCombines 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 StringSyntaxDescriptionExamplestd::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]OperatorsSyntaxDescriptionExampleoperator<<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, etcoperator<True if dp1.end() less than dp2.begin() dp1 < dp2, etcoperator>True if dp1.begin() greater than dp2.end()dp1 > dp2, etctop
Date IteratorsIntroduction -- Header -- OverviewIntroduction 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 OverviewClassConstruction ParametersDescriptiondate_iteratorCommon base class for all day level iterators.day_iteratordate start_date, int day_count=1Iterate day_count days at a time.week_iterator date start_date, int week_offset=1Iterate week_offset weeks at a time.month_iteratordate 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_iteratordate start_date, int year_offset=1Iterate 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/AlgorithmsDate Generators/AlgorithmsIntroduction -- Header -- Class Overview -- Function OverviewIntroduction 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" OverviewClassConstruction Parametersget_date ParameterDescriptionExampleyear_based_generatorabstract base classgreg_year yearA 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_monthgreg_weekday or weekday, greg_month or monthgreg_year or yearCalculate 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_monthgreg_weekday or weekday, greg_month or monthgreg_year or yearCalculate 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_dategreg_day, greg_month or monthgreg_yearGenerates 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 weekdaydateCalculate 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 weekdaydateCalculate 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 OverviewFunction PrototypeDescriptionExampledays 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 CalendarIntroduction -- Header -- FunctionsIntroduction 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 FunctionsSyntaxDescriptionExamplestatic short day_of_week(ymd_type)Return the day of the week (0==Sunday, 1==Monday, etc)See also gregorian::date day_of_weekstatic 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) --> truetop
Class day_clockClass day_clock
top
Posix TimePosix Time SystemIntroduction -- Usage ExamplesIntroduction 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 ExamplesExampleDescriptionTime MathA few simple calculations using ptime and time_durations.Print HoursRetrieve time from clock, use a time_iterator.Local to UTC ConversionDemonstrates a couple different ways to convert a local to UTC time including daylight savings rules.Time PeriodsSome simple examples of intersection and display of time periods.
Ptime ClassIntroduction -- Header -- Construction -- Construct from String -- Construct from Clock -- Construct using Conversion functions -- Accessors -- Conversion To String -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampleptime(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 constructorptime 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_timeConstruct from StringSyntaxDescriptionExampleptime 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 ClockSyntaxDescriptionExamplestatic 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 FunctionsSyntaxDescriptionExampleptime 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);AccessorsSyntaxDescriptionExampledate date() constGet 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() constGet 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 StringSyntaxDescriptionExamplestd::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.123456789std::string to_iso_string(ptime)Convert to form YYYYMMDDTHHMMSS,fffffffff where T is the date-time separator20020131T100001,123456789std::string to_iso_extended_string(ptime)Convert to form YYYY-MM-DDTHH:MM:SS,fffffffff where T is the date-time separator2002-01-31T10:00:01,123456789OperatorsSyntaxDescriptionExample operator==, operator!=, operator>, operator< operator>=, operator<= A full complement of comparison operatorst1 == t2, etcptime operator+(date_duration) constReturn 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) constReturn 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) constReturn 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) constReturn 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) constTake 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 DurationIntroduction -- Header -- Construction -- Count Based Construction -- Construct from String -- Accessors -- Conversion To String -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampletime_duration(hours,minutes,seconds,fractional_seconds)Construct ad duration from the countstime_duration td(1,2,3,9); //1 hr 2 min 3 sec 9 nanosecondsCount Based ConstructionSyntaxDescriptionExamplehours(long)Number of hourstime_duration td = hours(3);minutes(long)Number of minutestime_duration td = minutes(3);seconds(long) Number of secondstime_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 StringSyntaxDescriptionExampletime_duration duration_from_string(const std::string&)From delimited string. std::string ts("23:59:59.000"); time_duration td(duration_from_string(ts)) AccessorsSyntaxDescriptionExamplelong hours() constGet the number of normalized hours.time_duration td(1,2,3); td.hours() --> 1long minutes() constGet the number of minutes normalized (0..59).time_duration td(1,2,3); td.minutes() --> 2long seconds() constGet the normalized number of second (0..59).time_duration td(1,2,3); td.seconds() --> 3long total_seconds() constGet 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() constGet the number of fractional seconds.time_duration td(1,2,3, 1000); td.fractional_seconds() --> 1000bool is_negative() constTrue if duration is negative.time_duration td(-1,0,0); td.is_negative() --> truetime_duration invert_sign() constGenerate a new duration with the sign inverted/time_duration td(-1,0,0); td.invert_sign() --> 01:00:00static 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() --> nanostatic 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() --> 1000static time_duration unit()Return smallest possible unit of duration type (1 nanosecond).time_duration::unit() --> time_duration(0,0,0,1)Conversion To StringSyntaxDescriptionExamplestd::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.123456789std::string to_iso_string(time_duration)Convert to form HHMMSS,fffffffff.100001,123456789OperatorsSyntaxDescriptionExample operator==, operator!=, operator>, operator< operator>=, operator<= A full complement of comparison operatorsdd1 == dd2, etctime_duration operator+(time_duration) constAdd durations. time_duration td1(hours(1)+minutes(2)); time_duration td2(seconds(10)); time_duration td3 = td1 + td2; time_duration operator-(time_duration) constSubtract durations. time_duration td1(hours(1)+nanosec(2)); time_duration td2 = td1 - minutes(1); time_duration operator/(int) constDivide 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) constMultiply the length of a duration by an integer value.hours(3)*2 == hours(6);top
Time PeriodIntroduction -- Header -- Construction -- Accessors -- Conversion To String -- OperatorsIntroduction 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 ConstructionSyntaxDescriptionExampletime_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 constructortime_period tp1(tp)AccessorsSyntaxDescriptionExampleptime begin() constReturn 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() constReturn 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() constReturn 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() constTrue if period is not well formed. eg: start less than endbool contains(ptime) constTrue 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) constTrue 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) constCalculate the intersection of 2 periods. Null if no intersection.time_period merge(time_period) constReturns union of two periods. Null if no intersection.time_period span(time_period) constCombines 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 StringSyntaxDescriptionExamplestd::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]OperatorsSyntaxDescriptionExampleoperator<<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.lastif (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) {... etcoperator<=, operator>=Defined in terms of the other operators.top
Time IteratorsIntroduction -- Header -- Overview -- OperatorsIntroduction 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 OverviewClassConstruction ParametersDescriptiontime_iteratorptime start_time, time_duration incrementIterate incrementing by the specified duration.OperatorsSyntaxDescriptionExample 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 incrementIncrement the iterator by the specified duration. //increment by 10 milli seconds time_iterator titr(start_time, milliseconds(10)); ++titr; // == start_time + 10 milliseconds prefix decrementDecrement 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 secondstop
Local Time AdjustmentIntroduction -- Header -- OverviewIntroduction 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 OverviewClassDescriptionExampledate_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 offsetexampledate_time::local_adjustor<ptime, utc_offset, dst_rules>::local_to_utc(ptime)Calculate UTC time based on daylight savings rules and utc offset.exampletop
Details
CalculationsTimepoints -- Durations -- Intervals (Periods) -- Special Value HandlingTimepoints 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 GoalsCategoryDescriptionFunctionsInterfacesProvide 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 CalculationProvide a basis for performing efficient time calculations days between dates durations of times durations of dates and times together Representation FlexibilityProvide 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 CalculationsProvide tools for date calculationsprovide basis for calculation of complex event specs like holidayscalendar to calendar conversionsprovide for ability to extend to new calendar systemsTime CalculationsProvide concrete classes for manipulation of timeprovide the ability to handle cross time-zone issuesprovide adjustments for daylight savings time (summer time)Clock InterfacesProvide classes for retrieving time current timeaccess to a network / high resolution time sources retrieving the current date time information to populate classes I/O InterfacesProvide input and output for time includingmulti-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 timeaccurate math, e.g. duration calculationsability 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, andfor all t < ti, is_member( xi, t ) returns dont_know, andfor 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, andduration 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, andduration 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::gregoriandatedate_durationdate_periodpartial_datenth_day_of_week_in_monthfirst_day_of_week_in_monthlast_day_of_week_in_monthfirst_day_of_week_beforefirst_day_of_week_aftergreg_monthgreg_daygreg_weekdayboost::posix_timeptimetime_durationtime_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 hoursTime 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.
ReferencesDate ReferencesTime ReferencesOther C/C++ LibrariesJAVA Date-Time LibrariesScripting Language LibrariesRelated Commercial and Fanciful PagesResolution, Precision, and AccuracyDate Calendar ReferencesISO 8601 date time standard -- Summary by Markus KuhnCalendrical Calculations book by Reingold & DershowitzCalendar FAQ by Claus TønderingCalendar zone XML schema for date timeWill Linden's Calendar LinksXMAS calendar meltTimeMartin Folwer on time patterns Recurring Events for CalendarsPatterns for things that Change with timeUS National Institute of Standards and Technology Time ExhibitsNetwork Time Protocol at NTP.orgUS Navy Systems of TimeInternational Atomic TimeDate-Time type PostgreSQL User Guide Other C/C++ Librariesctime C Standard library reference at cplusplus.comXTime C extension proposalAnother C library extension proposal by David TribblelibTAI is a C based time libraryTime Zone Database C library for managing timezones/placesInternational Components for Unicode by IBM (open source) Calendar ClassDate Time ServicesTime Zone ClassDate-Time FormattingJulian Library in C by Mark Showalter -- NASAJAVA Date & Time Library Quick ReferenceCalendar classGregorian calendarDate classsql.time classDate format symbolsDate formatSimple Date FormatSimple Time ZoneScripting Language LibrariesA python date library MX Date TimePerl date-time Date-Time packages at CPANDate::Calc at CPANDate::Convert calendar conversions at CPANA PHP library Vlib Date LibraryRelated Commercial and Fanciful PagesLeapsecond.com time pageWorld Time Server / TZ database10000 year clock at Long Now FoundationTimezones for PCsResolution, Precision, and AccuracyDefinitions with pictures from Agilent TechnologiesAnother set of pictures from Team LabsDefinitions from Southampton InstituteDefinitions from Newport Corporation in the context of instrumentation
Build-Compiler InformationOverview -- Compilation Options -- Compiler/Portability Notes -- Directory Structure -- Required Boost LibrariesOverview 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 LinuxGCC 2.95.3 with STLport-4.5.3 on LinuxGCC 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 LinuxBorland 5.1.1 and 5.6MSVC 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.tokenizerboost.integer(cstdint)boost.operatorsboost::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 HistoryChanges from Boost 1.31 to 1.32 (date_time 1.02 to 1.03)TypeDescriptionBug FixSnap 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. FeatureFree function for creating a ptime object from a FILETIME struct. This function is only available on platforms that define BOOST_HAS_FTIME. FeatureMicrosecond time clock is now available on most windows compilers as well as Unix. FeatureUse 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. FeatureFunctions 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. FeaturePeriod 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. FeatureAdded 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 FixRemoved incorrect usage of BOOST_NO_CWCHAR macro throughout library. FeatureNew names added for some date classes. Original names are still valid but may some day be deprecated. Changes are: date_durationis nowdaysnth_kday_of_monthis nownth_day_of_the_week_in_monthfirst_kday_of_monthis nowfirst_day_of_the_week_in_monthlast_kday_of_monthis nowlast_day_of_the_week_in_monthfirst_kday_afteris nowfirst_day_of_the_week_afterfirst_kday_beforeis nowfirst_day_of_the_week_beforeFeatureFree 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. FeatureNew 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. FeatureUnifying base class for date_generators brought in to gregorian namespace. See Print Holidays Example. FeatureAdded 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. FeatureOutput 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. FeatureInput 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 FixFixed 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)TypeDescriptionBug FixBuild configuration updated so dll, statically, and dynamically linkable library files are now produced with MSVC compilers. See Build/Compiler Information for more details.Bug FixTime_duration from_string is now correctly constructed from a negative value. (ie "-0:39:00.000") Code provided by Bart Garst.Bug FixFixed many MSVC compiler warnings when compiled with warning level 4.FeatureAdded prefix decrement operator (--) for date and time iterators. See Time Iterators and Date Iterators for more details. Code provided by Bart Garst.FeatureSpecial_values functionality added for date_duration, time_duration and time classes. Code provided by Bart Garst.Bug FixFixed 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 FixProvided 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 FixAdded typedefs to boost::gregorian gregorian_types.hpp various date_generator function classes.FeatureAdded from_time_t function to convert time_t to a ptime.FeatureAdded a span function for combining periods. See date period and time period docs.FeatureAdded 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 FeatureAdded output streaming operators for the date generator classes - partial_date, first_kday_after, first_kday_before, etc. Thanks to Bart Garst for this work.FeatureAdded 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.FeatureAdded 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.FeatureIn 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-FixVarious 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); TypeDescriptionBug FixAdded new experimental feature for Daylight Savings Time calculations. This allows traits based specification of dst rules.FeatureAdded new interfaces to calculate julian day and modified julian day to the gregorian date class. See boost::gregorian::date.FeatureAdd new interface to calculate iso 8601 week number for a date. See boost::gregorian::date.FeatureAdd 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 FixSplit Jamfiles so that libs/date_time/build/Jamfile only builds library and /libs/date_time/libs/test/Jamfile which runs tests.Bug FixFixed many minor documentation issues.Bug FixRemoved the DATE_TIME_INLINE macro which was causing link errors. This macro is no longer needed in projects using the library.Bug FixAdded missing typedef for year_iterator to gregorian_types.hppBug FixFixed problem with gregorian ostream operators that prevented the use of wide streams.Bug-FixTighten 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
Library Reference The following is a detailed reference of the date_time library. A click on any of the reference links will take you to a list of the header files found in that section. Following one of those links will take you to a list of the items declared in that header file. Further sublinks take you to detailed descriptions of each individual item.
Date Time Reference
Header <<ulink url="../../boost/date_time/adjust_functors.hpp">boost/date_time/adjust_functors.hpp</ulink>>namespace boost {   namespace date_time {     template<typename date_type> class day_functor;     template<typename date_type> class month_functor;     template<typename date_type> class week_functor;     template<typename date_type> class year_functor;   } }Class template day_functor3boost::date_time::day_functorFunctor to iterate a fixed number of days. template<typename date_type> class day_functor { public:   // types   typedef date_type::duration_type duration_type;   // construct/copy/destruct   day_functor(int);   // public member functions   duration_type get_offset(const date_type &) const;   duration_type get_neg_offset(const date_type &) const; };Description<anchor id="day_functorconstruct-copy-destruct"/><computeroutput>day_functor</computeroutput> construct/copy/destructday_functor(int f);<anchor id="id374751-bb"/><computeroutput>day_functor</computeroutput> public member functionsduration_type get_offset(const date_type & d) const;duration_type get_neg_offset(const date_type & d) const;Class template month_functor3boost::date_time::month_functorProvides calculation to find next nth month given a date. template<typename date_type> class month_functor { public:   // types   typedef date_type::duration_type duration_type;   typedef date_type::calendar_type cal_type;        typedef cal_type::ymd_type       ymd_type;        typedef cal_type::day_type       day_type;        // construct/copy/destruct   month_functor(int);   // public member functions   duration_type get_offset(const date_type &) const;   duration_type get_neg_offset(const date_type &) const; };DescriptionThis adjustment function provides the logic for 'month-based' advancement on a ymd based calendar. The policy it uses to handle the non existant end of month days is to back up to the last day of the month. Also, if the starting date is the last day of a month, this functor will attempt to adjust to the end of the month. <anchor id="month_functorconstruct-copy-destruct"/><computeroutput>month_functor</computeroutput> construct/copy/destructmonth_functor(int f);<anchor id="id349946-bb"/><computeroutput>month_functor</computeroutput> public member functionsduration_type get_offset(const date_type & d) const;duration_type get_neg_offset(const date_type & d) const;Returns a negative duration_type. Class template week_functor3boost::date_time::week_functorFunctor to iterate a over weeks. template<typename date_type> class week_functor { public:   // types   typedef date_type::duration_type duration_type;   typedef date_type::calendar_type calendar_type;   // construct/copy/destruct   week_functor(int);   // public member functions   duration_type get_offset(const date_type &) const;   duration_type get_neg_offset(const date_type &) const; };Description<anchor id="week_functorconstruct-copy-destruct"/><computeroutput>week_functor</computeroutput> construct/copy/destructweek_functor(int f);<anchor id="id435416-bb"/><computeroutput>week_functor</computeroutput> public member functionsduration_type get_offset(const date_type & d) const;duration_type get_neg_offset(const date_type & d) const;Class template year_functor3boost::date_time::year_functorFunctor to iterate by a year adjusting for leap years. template<typename date_type> class year_functor { public:   // types   typedef date_type::duration_type duration_type;   // construct/copy/destruct   year_functor(int);   // public member functions   duration_type get_offset(const date_type &) const;   duration_type get_neg_offset(const date_type &) const; };Description<anchor id="year_functorconstruct-copy-destruct"/><computeroutput>year_functor</computeroutput> construct/copy/destructyear_functor(int f);<anchor id="id312559-bb"/><computeroutput>year_functor</computeroutput> public member functionsduration_type get_offset(const date_type & d) const;duration_type get_neg_offset(const date_type & d) const;
Header <<ulink url="../../boost/date_time/c_local_time_adjustor.hpp">boost/date_time/c_local_time_adjustor.hpp</ulink>>Time adjustment calculations based on machinenamespace boost {   namespace date_time {     template<typename time_type> class c_local_adjustor;   } }Class template c_local_adjustor3boost::date_time::c_local_adjustorAdjust to / from utc using the C API. template<typename time_type> class c_local_adjustor { public:   // types   typedef time_type::time_duration_type time_duration_type;   typedef time_type::date_type          date_type;            typedef date_type::duration_type      date_duration_type;   // public static functions   time_type utc_to_local(const time_type &) ; };DescriptionWarning!!! This class assumes that timezone settings of the machine are correct. This can be a very dangerous assumption. <anchor id="id317142-bb"/><computeroutput>c_local_adjustor</computeroutput> public static functionstime_type utc_to_local(const time_type & t) ;Convert a utc time to local time.
Header <<ulink url="../../boost/date_time/c_time.hpp">boost/date_time/c_time.hpp</ulink>>Provide workarounds related to the ctime headernamespace std { }
Header <<ulink url="../../boost/date_time/compiler_config.hpp">boost/date_time/compiler_config.hpp</ulink>>namespace std { }
Header <<ulink url="../../boost/date_time/constrained_value.hpp">boost/date_time/constrained_value.hpp</ulink>>namespace boost {   namespace CV {     template<typename value_policies> class constrained_value;     template<typename rep_type, rep_type min_value, rep_type max_value,              typename exception_type>     class simple_exception_policy;     // Represent a min or max violation type.     enum violation_enum { min_violation, max_violation };   } }Class template constrained_value3boost::CV::constrained_valueA template to specify a constrained basic value type. template<typename value_policies> class constrained_value { public:   // types   typedef value_policies::value_type value_type;   // construct/copy/destruct   constrained_value(value_type);   constrained_value& operator=(value_type);   // public member functions   operator value_type() const;   // public static functions   value_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;   value_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;   // private member functions   void assign(value_type) ; };DescriptionThis template provides a quick way to generate an integer type with a constrained range. The type provides for the ability to specify the min, max, and and error handling policy.value policies A class that provides the range limits via the min and max functions as well as a function on_error that determines how errors are handled. A common strategy would be to assert or throw and exception. The on_error is passed both the current value and the new value that is in error. <anchor id="constrained_valueconstruct-copy-destruct"/><computeroutput>constrained_value</computeroutput> construct/copy/destructconstrained_value(value_type value);constrained_value& operator=(value_type v);<anchor id="id405391-bb"/><computeroutput>constrained_value</computeroutput> public member functionsoperator value_type() const;Coerce into the representation type. <anchor id="id315083-bb"/><computeroutput>constrained_value</computeroutput> public static functionsvalue_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;Return the max allowed value (traits method). value_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;Return the min allowed value (traits method). <anchor id="id336013-bb"/><computeroutput>constrained_value</computeroutput> private member functionsvoid assign(value_type value) ;Class template simple_exception_policy3boost::CV::simple_exception_policyTemplate to shortcut the constrained_value policy creation process. template<typename rep_type, rep_type min_value, rep_type max_value,          typename exception_type> class simple_exception_policy { public:   // types   typedef rep_type value_type;   // public static functions   rep_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;   rep_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;   void on_error(rep_type, rep_type, violation_enum) ; };Description<anchor id="id353157-bb"/><computeroutput>simple_exception_policy</computeroutput> public static functionsrep_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;rep_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;void on_error(rep_type , rep_type , violation_enum ) ;
Header <<ulink url="../../boost/date_time/date.hpp">boost/date_time/date.hpp</ulink>>namespace boost {   namespace date_time {     template<typename T, typename calendar, typename duration_type_> class date;   } }Class template date3boost::date_time::dateRepresentation of timepoint at the one day level resolution. template<typename T, typename calendar, typename duration_type_> class date { public:   // types   typedef T                          date_type;          typedef calendar                   calendar_type;      typedef calendar::date_traits_type traits_type;        typedef duration_type_             duration_type;      typedef calendar::year_type        year_type;          typedef calendar::month_type       month_type;         typedef calendar::day_type         day_type;           typedef calendar::ymd_type         ymd_type;           typedef calendar::date_rep_type    date_rep_type;      typedef calendar::date_int_type    date_int_type;      typedef calendar::day_of_week_type day_of_week_type;   // construct/copy/destruct   date(year_type, month_type, day_type);   date(const ymd_type &);   date(date_int_type);   date(date_rep_type);   // public member functions   year_type year() const;   month_type month() const;   day_type day() const;   day_of_week_type day_of_week() const;   ymd_type year_month_day() const;   bool operator<(const date_type &) const;   bool operator==(const date_type &) const;   bool is_special() const;   bool is_not_a_date() const;   bool is_infinity() const;   bool is_pos_infinity() const;   bool is_neg_infinity() const;   special_values as_special() const;   duration_type operator-(const date_type &) const;   date_type operator-(const duration_type &) const;   date_type operator-=(const duration_type &) ;   date_rep_type day_count() const;   date_type operator+(const duration_type &) const;   date_type operator+=(const duration_type &) ;   // protected member functions };DescriptionThe date template represents an interface shell for a date class that is based on a year-month-day system such as the gregorian or iso systems. It provides basic operations to enable calculation and comparisons.TheoryThis date representation fundamentally departs from the C tm struct approach. The goal for this type is to provide efficient date operations (add, subtract) and storage (minimize space to represent) in a concrete class. Thus, the date uses a count internally to represent a particular date. The calendar parameter defines the policies for converting the the year-month-day and internal counted form here. Applications that need to perform heavy formatting of the same date repeatedly will perform better by using the year-month-day representation.Internally the date uses a day number to represent the date. This is a monotonic time representation. This representation allows for fast comparison as well as simplifying the creation of writing numeric operations. Essentially, the internal day number is like adjusted julian day. The adjustment is determined by the Epoch date which is represented as day 1 of the calendar. Day 0 is reserved for negative infinity so that any actual date is automatically greater than negative infinity. When a date is constructed from a date or formatted for output, the appropriate conversions are applied to create the year, month, day representations. <anchor id="boost.date_time.dateconstruct-copy-destruct"/><computeroutput>date</computeroutput> construct/copy/destructdate(year_type y, month_type m, day_type d);date(const ymd_type & ymd);date(date_int_type days);This is a private constructor which allows for the creation of new dates. It is not exposed to users since that would require class users to understand the inner workings of the date class. date(date_rep_type days);<anchor id="id397241-bb"/><computeroutput>date</computeroutput> public member functionsyear_type year() const;month_type month() const;day_type day() const;day_of_week_type day_of_week() const;ymd_type year_month_day() const;bool operator<(const date_type & rhs) const;bool operator==(const date_type & rhs) const;bool is_special() const;check to see if date is a special value bool is_not_a_date() const;check to see if date is not a value bool is_infinity() const;check to see if date is one of the infinity values bool is_pos_infinity() const;check to see if date is greater than all possible dates bool is_neg_infinity() const;check to see if date is greater than all possible dates special_values as_special() const;return as a special value or a not_special if a normal date duration_type operator-(const date_type & d) const;date_type operator-(const duration_type & dd) const;date_type operator-=(const duration_type & dd) ;date_rep_type day_count() const;date_type operator+(const duration_type & dd) const;date_type operator+=(const duration_type & dd) ;<anchor id="id401946-bb"/><computeroutput>date</computeroutput> protected member functions
Header <<ulink url="../../boost/date_time/date_clock_device.hpp">boost/date_time/date_clock_device.hpp</ulink>>namespace boost {   namespace date_time {     template<typename date_type> class day_clock;   } }Class template day_clock3boost::date_time::day_clockA clock providing day level services based on C time_t capabilities. template<typename date_type> class day_clock { public:   // types   typedef date_type::ymd_type ymd_type;   // public static functions   date_type local_day() ;   date_type::ymd_type local_day_ymd() ;   date_type::ymd_type universal_day_ymd() ;   date_type universal_day() ;   // private static functions   ::std::tm * get_local_time() ;   ::std::tm * get_universal_time() ; };DescriptionThis clock uses Posix interfaces as its implementation and hence uses the timezone settings of the operating system. Incorrect user settings will result in incorrect results for the calls to local_day. <anchor id="id423222-bb"/><computeroutput>day_clock</computeroutput> public static functionsdate_type local_day() ;Get the local day as a date type. date_type::ymd_type local_day_ymd() ;Get the local day as a ymd_type. date_type::ymd_type universal_day_ymd() ;Get the current day in universal date as a ymd_type. date_type universal_day() ;Get the UTC day as a date type. <anchor id="id329464-bb"/><computeroutput>day_clock</computeroutput> private static functions::std::tm * get_local_time() ;::std::tm * get_universal_time() ;
Header <<ulink url="../../boost/date_time/date_defs.hpp">boost/date_time/date_defs.hpp</ulink>>namespace boost {   namespace date_time {     // An enumeration of weekday names.     enum weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,                     Saturday };     // Simple enum to allow for nice programming with Jan, Feb, etc.     enum months_of_year { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct,                           Nov, Dec, NotAMonth, NumMonths };   } }
Header <<ulink url="../../boost/date_time/date_duration.hpp">boost/date_time/date_duration.hpp</ulink>>namespace boost {   namespace date_time {     template<typename duration_rep_traits> class date_duration;     struct duration_traits_long;     struct duration_traits_adapted;   } }Class template date_duration3boost::date_time::date_durationDuration type with date level resolution. template<typename duration_rep_traits> class date_duration { public:   // types   typedef duration_rep_traits::int_type  duration_rep_type;   typedef duration_rep_traits::impl_type duration_rep;        // construct/copy/destruct   date_duration(duration_rep);   date_duration(special_values);   date_duration(const date_duration< duration_rep_traits > &);   // public member functions   duration_rep get_rep() const;   bool is_special() const;   duration_rep_type days() const;   bool operator==(const date_duration &) const;   bool operator<(const date_duration &) const;   date_duration operator-=(const date_duration &) ;   date_duration operator+=(const date_duration &) ;   date_duration operator-() const;   date_duration< duration_rep_traits > operator/=(int) ;   date_duration< duration_rep_traits > operator/(int) ;   bool is_negative() const;   // public static functions   date_duration unit() ; };Description<anchor id="date_durationconstruct-copy-destruct"/><computeroutput>date_duration</computeroutput> construct/copy/destructdate_duration(duration_rep day_count);Construct from a day count. date_duration(special_values sv);construct from special_values - only works when instantiated with duration_traits_adapted date_duration(const date_duration< duration_rep_traits > & other);Construct from another date_duration (Copy Constructor). <anchor id="id423776-bb"/><computeroutput>date_duration</computeroutput> public member functionsduration_rep get_rep() const;returns days_ as it's instantiated type - used for streaming bool is_special() const;duration_rep_type days() const;returns days as value, not object. bool operator==(const date_duration & rhs) const;Equality. bool operator<(const date_duration & rhs) const;Less. date_duration operator-=(const date_duration & rhs) ;Subtract another duration -- result is signed. date_duration operator+=(const date_duration & rhs) ;Add a duration -- result is signed. date_duration operator-() const;unary- Allows for dd = -date_duration(2); -> dd == -2 date_duration< duration_rep_traits > operator/=(int divisor) ;Division operations on a duration with an integer. date_duration< duration_rep_traits > operator/(int divisor) ;bool is_negative() const;return sign information <anchor id="id400391-bb"/><computeroutput>date_duration</computeroutput> public static functionsdate_duration unit() ;Returns the smallest duration -- used by to calculate 'end'. Struct duration_traits_long3boost::date_time::duration_traits_long struct duration_traits_long {   // types   typedef long int_type;    typedef long impl_type;   // public static functions   int_type as_number(impl_type) ; };DescriptionStruct for instantiating date_duration with NO special values functionality. Allows for transparent implementation of either date_duration<long> or date_duration<int_adapter<long> > <anchor id="id413989-bb"/><computeroutput>duration_traits_long</computeroutput> public static functionsint_type as_number(impl_type i) ;Struct duration_traits_adapted3boost::date_time::duration_traits_adapted struct duration_traits_adapted {   // types   typedef long                                  int_type;    typedef boost::date_time::int_adapter< long > impl_type;   // public static functions   int_type as_number(impl_type) ; };DescriptionStruct for instantiating date_duration WITH special values functionality. Allows for transparent implementation of either date_duration<long> or date_duration<int_adapter<long> > <anchor id="id360428-bb"/><computeroutput>duration_traits_adapted</computeroutput> public static functionsint_type as_number(impl_type i) ;
Header <<ulink url="../../boost/date_time/date_duration_types.hpp">boost/date_time/date_duration_types.hpp</ulink>>namespace boost {   namespace date_time {     template<typename duration_config> class weeks_duration;     template<typename base_config> class months_duration;     template<typename base_config> class years_duration;   } }Class template weeks_duration3boost::date_time::weeks_durationAdditional duration type that represents a number of n*7 days. template<typename duration_config> class weeks_duration : : public boost::date_time::date_duration< duration_config > { public:   // construct/copy/destruct   weeks_duration(typename duration_config::impl_type);   weeks_duration(special_values);   // public member functions };Description<anchor id="weeks_durationconstruct-copy-destruct"/><computeroutput>weeks_duration</computeroutput> construct/copy/destructweeks_duration(typename duration_config::impl_type w);weeks_duration(special_values sv);<anchor id="id356004-bb"/><computeroutput>weeks_duration</computeroutput> public member functionsClass template months_duration3boost::date_time::months_durationadditional duration type that represents a logical month template<typename base_config> class months_duration { public:   // construct/copy/destruct   months_duration(int_rep);   months_duration(special_values);   // public member functions   int_rep number_of_months() const;   duration_type get_neg_offset(const date_type &) const;   duration_type get_offset(const date_type &) const;   bool operator==(const months_type &) const;   bool operator!=(const months_type &) const;   months_type operator+(const months_type &) const;   months_type & operator+=(const months_type &) ;   months_type operator-(const months_type &) const;   months_type & operator-=(const months_type &) ;   months_type operator *(const int_type) const;   months_type & operator *=(const int_type) ;   months_type operator/(const int_type) const;   months_type & operator/=(const int_type) ;   months_type operator+(const years_type &) const;   months_type & operator+=(const years_type &) ;   months_type operator-(const years_type &) const;   months_type & operator-=(const years_type &) ; };DescriptionA logical month enables things like: "date(2002,Mar,2) + months(2) -> 2002-May2". If the date is a last day-of-the-month, the result will also be a last-day-of-the-month. <anchor id="months_durationconstruct-copy-destruct"/><computeroutput>months_duration</computeroutput> construct/copy/destructmonths_duration(int_rep num);months_duration(special_values sv);<anchor id="id398297-bb"/><computeroutput>months_duration</computeroutput> public member functionsint_rep number_of_months() const;duration_type get_neg_offset(const date_type & d) const;returns a negative duration duration_type get_offset(const date_type & d) const;bool operator==(const months_type & rhs) const;bool operator!=(const months_type & rhs) const;months_type operator+(const months_type & rhs) const;months_type & operator+=(const months_type & rhs) ;months_type operator-(const months_type & rhs) const;months_type & operator-=(const months_type & rhs) ;months_type operator *(const int_type rhs) const;months_type & operator *=(const int_type rhs) ;months_type operator/(const int_type rhs) const;months_type & operator/=(const int_type rhs) ;months_type operator+(const years_type & y) const;months_type & operator+=(const years_type & y) ;months_type operator-(const years_type & y) const;months_type & operator-=(const years_type & y) ;Class template years_duration3boost::date_time::years_durationadditional duration type that represents a logical year template<typename base_config> class years_duration { public:   // construct/copy/destruct   years_duration(int_rep);   years_duration(special_values);   // public member functions   int_rep number_of_years() const;   duration_type get_neg_offset(const date_type &) const;   duration_type get_offset(const date_type &) const;   bool operator==(const years_type &) const;   bool operator!=(const years_type &) const;   years_type operator+(const years_type &) const;   years_type & operator+=(const years_type &) ;   years_type operator-(const years_type &) const;   years_type & operator-=(const years_type &) ;   years_type operator *(const int_type) const;   years_type & operator *=(const int_type) ;   years_type operator/(const int_type) const;   years_type & operator/=(const int_type) ;   months_type operator+(const months_type &) const;   months_type operator-(const months_type &) const; };DescriptionA logical year enables things like: "date(2002,Mar,2) + years(2) -> 2004-Mar-2". If the date is a last day-of-the-month, the result will also be a last-day-of-the-month (ie date(2001-Feb-28) + years(3) -> 2004-Feb-29). <anchor id="years_durationconstruct-copy-destruct"/><computeroutput>years_duration</computeroutput> construct/copy/destructyears_duration(int_rep num);years_duration(special_values sv);<anchor id="id385605-bb"/><computeroutput>years_duration</computeroutput> public member functionsint_rep number_of_years() const;duration_type get_neg_offset(const date_type & d) const;returns a negative duration duration_type get_offset(const date_type & d) const;bool operator==(const years_type & rhs) const;bool operator!=(const years_type & rhs) const;years_type operator+(const years_type & rhs) const;years_type & operator+=(const years_type & rhs) ;years_type operator-(const years_type & rhs) const;years_type & operator-=(const years_type & rhs) ;years_type operator *(const int_type rhs) const;years_type & operator *=(const int_type rhs) ;years_type operator/(const int_type rhs) const;years_type & operator/=(const int_type rhs) ;months_type operator+(const months_type & m) const;months_type operator-(const months_type & m) const;
Header <<ulink url="../../boost/date_time/date_format_simple.hpp">boost/date_time/date_format_simple.hpp</ulink>>namespace boost {   namespace date_time {     template<typename charT> class simple_format;     template<> class simple_format<wchar_t>;   } }Class template simple_format3boost::date_time::simple_formatClass to provide simple basic formatting rules. template<typename charT> class simple_format { public:   // public static functions   const charT * not_a_date() ;   const charT * pos_infinity() ;   const charT * neg_infinity() ;   month_format_spec month_format() ;   ymd_order_spec date_order() ;   bool has_date_sep_chars() ;   charT year_sep_char() ;   charT month_sep_char() ;   charT day_sep_char() ;   charT hour_sep_char() ;   charT minute_sep_char() ;   charT second_sep_char() ; };Description<anchor id="id393016-bb"/><computeroutput>simple_format</computeroutput> public static functionsconst charT * not_a_date() ;String used printed is date is invalid. const charT * pos_infinity() ;String used to for positive infinity value. const charT * neg_infinity() ;String used to for positive infinity value. month_format_spec month_format() ;Describe month format. ymd_order_spec date_order() ;bool has_date_sep_chars() ;This format uses '-' to separate date elements. charT year_sep_char() ;Char to sep? charT month_sep_char() ;char between year-month charT day_sep_char() ;Char to separate month-day. charT hour_sep_char() ;char between date-hours charT minute_sep_char() ;char between hour and minute charT second_sep_char() ;char for second SpecializationsClass simple_format<wchar_t>Class simple_format<wchar_t>3boost::date_time::simple_format<wchar_t>Specialization of formmating rules for wchar_t. class simple_format<wchar_t> { public:   // public static functions   const wchar_t * not_a_date() ;   const wchar_t * pos_infinity() ;   const wchar_t * neg_infinity() ;   month_format_spec month_format() ;   ymd_order_spec date_order() ;   bool has_date_sep_chars() ;   wchar_t year_sep_char() ;   wchar_t month_sep_char() ;   wchar_t day_sep_char() ;   wchar_t hour_sep_char() ;   wchar_t minute_sep_char() ;   wchar_t second_sep_char() ; };Description<anchor id="id417252-bb"/><computeroutput>simple_format</computeroutput> public static functionsconst wchar_t * not_a_date() ;String used printed is date is invalid. const wchar_t * pos_infinity() ;String used to for positive infinity value. const wchar_t * neg_infinity() ;String used to for positive infinity value. month_format_spec month_format() ;Describe month format. ymd_order_spec date_order() ;bool has_date_sep_chars() ;This format uses '-' to separate date elements. wchar_t year_sep_char() ;Char to sep? wchar_t month_sep_char() ;char between year-month wchar_t day_sep_char() ;Char to separate month-day. wchar_t hour_sep_char() ;char between date-hours wchar_t minute_sep_char() ;char between hour and minute wchar_t second_sep_char() ;char for second
Header <<ulink url="../../boost/date_time/date_formatting.hpp">boost/date_time/date_formatting.hpp</ulink>>namespace boost {   namespace date_time {     template<typename month_type, typename format_type, typename charT = char>     class month_formatter;     template<typename ymd_type, typename format_type, typename charT = char>     class ymd_formatter;     template<typename date_type, typename format_type, typename charT = char>     class date_formatter;   } }Class template month_formatter3boost::date_time::month_formatterFormats a month as as string into an ostream. template<typename month_type, typename format_type, typename charT = char> class month_formatter { public:   // public static functions   std::basic_ostream< charT > &   format_month(const month_type &, std::basic_ostream< charT > &) ;   std::ostream & format_month(const month_type &, std::ostream &) ; };Description<anchor id="id421978-bb"/><computeroutput>month_formatter</computeroutput> public static functionsstd::basic_ostream< charT > & format_month(const month_type & month, std::basic_ostream< charT > & os) ;Formats a month as as string into an ostream. This function demands that month_type provide functions for converting to short and long strings if that capability is used. std::ostream & format_month(const month_type & month, std::ostream & os) ;Formats a month as as string into an ostream. This function demands that month_type provide functions for converting to short and long strings if that capability is used. Class template ymd_formatter3boost::date_time::ymd_formatterConvert ymd to a standard string formatting policies. template<typename ymd_type, typename format_type, typename charT = char> class ymd_formatter { public:   // public static functions   std::basic_string< charT > ymd_to_string(ymd_type) ;   std::string ymd_to_string(ymd_type) ; };Description<anchor id="id403200-bb"/><computeroutput>ymd_formatter</computeroutput> public static functionsstd::basic_string< charT > ymd_to_string(ymd_type ymd) ;Convert ymd to a standard string formatting policies. This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy std::string ymd_to_string(ymd_type ymd) ;Convert ymd to a standard string formatting policies. This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy Class template date_formatter3boost::date_time::date_formatterConvert a date to string using format policies. template<typename date_type, typename format_type, typename charT = char> class date_formatter { public:   // types   typedef std::basic_string< charT > string_type;   // public static functions   string_type date_to_string(date_type) ;   std::string date_to_string(date_type) ; };Description<anchor id="id408662-bb"/><computeroutput>date_formatter</computeroutput> public static functionsstring_type date_to_string(date_type d) ;Convert to a date to standard string using format policies. std::string date_to_string(date_type d) ;Convert to a date to standard string using format policies.
Header <<ulink url="../../boost/date_time/date_formatting_limited.hpp">boost/date_time/date_formatting_limited.hpp</ulink>>namespace boost {   namespace date_time {   } }
Header <<ulink url="../../boost/date_time/date_formatting_locales.hpp">boost/date_time/date_formatting_locales.hpp</ulink>>namespace boost {   namespace date_time {     template<typename facet_type, typename charT = char>     class ostream_month_formatter;     template<typename weekday_type, typename facet_type,              typename charT = char>     class ostream_weekday_formatter;     template<typename ymd_type, typename facet_type, typename charT = char>     class ostream_ymd_formatter;     template<typename date_type, typename facet_type, typename charT = char>     class ostream_date_formatter;   } }Class template ostream_month_formatter3boost::date_time::ostream_month_formatterFormats a month as as string into an ostream. template<typename facet_type, typename charT = char> class ostream_month_formatter { public:   // types   typedef facet_type::month_type      month_type;     typedef std::basic_ostream< charT > ostream_type;   // public static functions   void format_month(const month_type &, ostream_type &, const facet_type &) ; };Description<anchor id="id419858-bb"/><computeroutput>ostream_month_formatter</computeroutput> public static functionsvoid format_month(const month_type & month, ostream_type & os,                   const facet_type & f) ;Formats a month as as string into an output iterator. Class template ostream_weekday_formatter3boost::date_time::ostream_weekday_formatterFormats a weekday. template<typename weekday_type, typename facet_type, typename charT = char> class ostream_weekday_formatter { public:   // types   typedef facet_type::month_type      month_type;     typedef std::basic_ostream< charT > ostream_type;   // public static functions   void format_weekday(const weekday_type &, ostream_type &,                       const facet_type &, bool) ; };Description<anchor id="id430414-bb"/><computeroutput>ostream_weekday_formatter</computeroutput> public static functionsvoid format_weekday(const weekday_type & wd, ostream_type & os,                     const facet_type & f, bool as_long_string) ;Formats a month as as string into an output iterator. Class template ostream_ymd_formatter3boost::date_time::ostream_ymd_formatterConvert ymd to a standard string formatting policies. template<typename ymd_type, typename facet_type, typename charT = char> class ostream_ymd_formatter { public:   // types   typedef ymd_type::month_type                         month_type;             typedef ostream_month_formatter< facet_type, charT > month_formatter_type;   typedef std::basic_ostream< charT >                  ostream_type;           typedef std::basic_string< charT >                   foo_type;               // public static functions   void ymd_put(ymd_type, ostream_type &, const facet_type &) ; };Description<anchor id="id401924-bb"/><computeroutput>ostream_ymd_formatter</computeroutput> public static functionsvoid ymd_put(ymd_type ymd, ostream_type & os, const facet_type & f) ;Convert ymd to a standard string formatting policies. This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy Class template ostream_date_formatter3boost::date_time::ostream_date_formatterConvert a date to string using format policies. template<typename date_type, typename facet_type, typename charT = char> class ostream_date_formatter { public:   // types   typedef std::basic_ostream< charT > ostream_type;   typedef date_type::ymd_type         ymd_type;       // public static functions   void date_put(const date_type &, ostream_type &, const facet_type &) ;   void date_put(const date_type &, ostream_type &) ; };Description<anchor id="id333524-bb"/><computeroutput>ostream_date_formatter</computeroutput> public static functionsvoid date_put(const date_type & d, ostream_type & os, const facet_type & f) ;Put date into an ostream. void date_put(const date_type & d, ostream_type & os) ;Put date into an ostream.
Header <<ulink url="../../boost/date_time/date_generators.hpp">boost/date_time/date_generators.hpp</ulink>>Definition and implementation of date algorithm templatesnamespace boost {   namespace date_time {     template<typename date_type> class year_based_generator;     template<typename date_type> class partial_date;     template<typename date_type> class nth_kday_of_month;     template<typename date_type> class first_kday_of_month;     template<typename date_type> class last_kday_of_month;     template<typename date_type> class first_kday_after;     template<typename date_type> class first_kday_before;     // Returns nth arg as string. 1 -> "first", 2 -> "second", max is 5.     BOOST_DATE_TIME_DECL const char * nth_as_str(int n);     template<typename date_type, typename weekday_type>       date_type::duration_type       days_until_weekday(const date_type &, const weekday_type &);     template<typename date_type, typename weekday_type>       date_type::duration_type       days_before_weekday(const date_type &, const weekday_type &);     template<typename date_type, typename weekday_type>       date_type next_weekday(const date_type &, const weekday_type &);     template<typename date_type, typename weekday_type>       date_type previous_weekday(const date_type &, const weekday_type &);   } }Class template year_based_generator3boost::date_time::year_based_generatorBase class for all generators that take a year and produce a date. template<typename date_type> class year_based_generator { public:   // types   typedef date_type::calendar_type calendar_type;   typedef calendar_type::year_type year_type;       // construct/copy/destruct   year_based_generator();   ~year_based_generator();   // public member functions   virtual date_type get_date(year_type) const; };DescriptionThis class is a base class for polymorphic function objects that take a year and produce a concrete date. <anchor id="year_based_generatorconstruct-copy-destruct"/><computeroutput>year_based_generator</computeroutput> construct/copy/destructyear_based_generator();~year_based_generator();<anchor id="id313666-bb"/><computeroutput>year_based_generator</computeroutput> public member functionsvirtual date_type get_date(year_type y) const;Class template partial_date3boost::date_time::partial_dateGenerates a date by applying the year to the given month and day. template<typename date_type> class partial_date : : public boost::date_time::year_based_generator< date_type > { public:   // types   typedef date_type::calendar_type    calendar_type;   typedef calendar_type::day_type     day_type;        typedef calendar_type::month_type   month_type;      typedef calendar_type::year_type    year_type;       typedef date_type::duration_type    duration_type;   typedef duration_type::duration_rep duration_rep;    // construct/copy/destruct   partial_date(day_type, month_type);   partial_date(duration_rep);   // public member functions   date_type get_date(year_type) const;   date_type operator()(year_type) const;   bool operator==(const partial_date &) const;   bool operator<(const partial_date &) const;   month_type month() const;   day_type day() const; };DescriptionExample usage: partial_date pd(1, Jan); partial_date pd2(70); date d = pd.get_date(2002); //2002-Jan-01 date d2 = pd2.get_date(2002); //2002-Mar-10 <anchor id="partial_dateconstruct-copy-destruct"/><computeroutput>partial_date</computeroutput> construct/copy/destructpartial_date(day_type d, month_type m);partial_date(duration_rep days);Partial date created from number of days into year. Range 1-366. Allowable values range from 1 to 366. 1=Jan1, 366=Dec31. If argument exceeds range, partial_date will be created with closest in-range value. 60 will always be Feb29, if get_date() is called with a non-leap year an exception will be thrown <anchor id="id308312-bb"/><computeroutput>partial_date</computeroutput> public member functionsdate_type get_date(year_type y) const;Return a concrete date when provided with a year specific year. Will throw an 'invalid_argument' exception if a partial_date object, instantiated with Feb-29, has get_date called with a non-leap year. Example: partial_date pd(29, Feb); pd.get_date(2003); // throws invalid_argument exception pg.get_date(2000); // returns 2000-2-29 date_type operator()(year_type y) const;bool operator==(const partial_date & rhs) const;bool operator<(const partial_date & rhs) const;month_type month() const;day_type day() const;Class template nth_kday_of_month3boost::date_time::nth_kday_of_monthUseful generator functor for finding holidays. template<typename date_type> class nth_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public:   // types   typedef date_type::calendar_type        calendar_type;      typedef calendar_type::day_of_week_type day_of_week_type;   typedef calendar_type::month_type       month_type;         typedef calendar_type::year_type        year_type;          typedef date_type::duration_type        duration_type;      // construct/copy/destruct   nth_kday_of_month(week_num, day_of_week_type, month_type);   // public member functions   date_type get_date(year_type) const;   month_type month() const;   week_num nth_week() const;   day_of_week_type day_of_week() const;   const char * nth_week_as_str() const; };DescriptionBased on the idea in Cal. Calc. for finding holidays that are the 'first Monday of September'. When instantiated with 'fifth' kday of month, the result will be the last kday of month which can be the fourth or fifth depending on the structure of the month.The algorithm here basically guesses for the first day of the month. Then finds the first day of the correct type. That is, if the first of the month is a Tuesday and it needs Wenesday then we simply increment by a day and then we can add the length of a week until we get to the 'nth kday'. There are probably more efficient algorithms based on using a mod 7, but this one works reasonably well for basic applications. <anchor id="nth_kday_of_monthconstruct-copy-destruct"/><computeroutput>nth_kday_of_month</computeroutput> construct/copy/destructnth_kday_of_month(week_num week_no, day_of_week_type dow, month_type m);<anchor id="id309002-bb"/><computeroutput>nth_kday_of_month</computeroutput> public member functionsdate_type get_date(year_type y) const;Return a concrete date when provided with a year specific year. month_type month() const;week_num nth_week() const;day_of_week_type day_of_week() const;const char * nth_week_as_str() const;Class template first_kday_of_month3boost::date_time::first_kday_of_monthUseful generator functor for finding holidays and daylight savings. template<typename date_type> class first_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public:   // types   typedef date_type::calendar_type        calendar_type;      typedef calendar_type::day_of_week_type day_of_week_type;   typedef calendar_type::month_type       month_type;         typedef calendar_type::year_type        year_type;          typedef date_type::duration_type        duration_type;      // construct/copy/destruct   first_kday_of_month(day_of_week_type, month_type);   // public member functions   date_type get_date(year_type) const;   month_type month() const;   day_of_week_type day_of_week() const; };DescriptionSimilar to nth_kday_of_month, but requires less paramters <anchor id="first_kday_of_monthconstruct-copy-destruct"/><computeroutput>first_kday_of_month</computeroutput> construct/copy/destructfirst_kday_of_month(day_of_week_type dow, month_type m);Specify the first 'Sunday' in 'April' spec. ParametersdowThe day of week, eg: Sunday, Monday, etc mThe month of the year, eg: Jan, Feb, Mar, etc <anchor id="id390234-bb"/><computeroutput>first_kday_of_month</computeroutput> public member functionsdate_type get_date(year_type year) const;Return a concrete date when provided with a year specific year. month_type month() const;day_of_week_type day_of_week() const;Class template last_kday_of_month3boost::date_time::last_kday_of_monthCalculate something like Last Sunday of January. template<typename date_type> class last_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public:   // types   typedef date_type::calendar_type        calendar_type;      typedef calendar_type::day_of_week_type day_of_week_type;   typedef calendar_type::month_type       month_type;         typedef calendar_type::year_type        year_type;          typedef date_type::duration_type        duration_type;      // construct/copy/destruct   last_kday_of_month(day_of_week_type, month_type);   // public member functions   date_type get_date(year_type) const;   month_type month() const;   day_of_week_type day_of_week() const; };DescriptionUseful generator functor for finding holidays and daylight savings Get the last day of the month and then calculate the difference to the last previous day. <anchor id="last_kday_of_monthconstruct-copy-destruct"/><computeroutput>last_kday_of_month</computeroutput> construct/copy/destructlast_kday_of_month(day_of_week_type dow, month_type m);Specify the date spec like last 'Sunday' in 'April' spec. ParametersdowThe day of week, eg: Sunday, Monday, etc mThe month of the year, eg: Jan, Feb, Mar, etc <anchor id="id404786-bb"/><computeroutput>last_kday_of_month</computeroutput> public member functionsdate_type get_date(year_type year) const;Return a concrete date when provided with a year specific year. month_type month() const;day_of_week_type day_of_week() const;Class template first_kday_after3boost::date_time::first_kday_afterCalculate something like "First Sunday after Jan 1,2002. template<typename date_type> class first_kday_after { public:   // types   typedef date_type::calendar_type        calendar_type;      typedef calendar_type::day_of_week_type day_of_week_type;   typedef date_type::duration_type        duration_type;      // construct/copy/destruct   first_kday_after(day_of_week_type);   // public member functions   date_type get_date(date_type) const;   day_of_week_type day_of_week() const; };DescriptionDate generator that takes a date and finds kday after typedef boost::date_time::first_kday_after<date> firstkdayafter; firstkdayafter fkaf(Monday); fkaf.get_date(date(2002,Feb,1)); <anchor id="first_kday_afterconstruct-copy-destruct"/><computeroutput>first_kday_after</computeroutput> construct/copy/destructfirst_kday_after(day_of_week_type dow);<anchor id="id412058-bb"/><computeroutput>first_kday_after</computeroutput> public member functionsdate_type get_date(date_type start_day) const;Return next kday given. day_of_week_type day_of_week() const;Class template first_kday_before3boost::date_time::first_kday_beforeCalculate something like "First Sunday before Jan 1,2002. template<typename date_type> class first_kday_before { public:   // types   typedef date_type::calendar_type        calendar_type;      typedef calendar_type::day_of_week_type day_of_week_type;   typedef date_type::duration_type        duration_type;      // construct/copy/destruct   first_kday_before(day_of_week_type);   // public member functions   date_type get_date(date_type) const;   day_of_week_type day_of_week() const; };DescriptionDate generator that takes a date and finds kday after typedef boost::date_time::first_kday_before<date> firstkdaybefore; firstkdaybefore fkbf(Monday); fkbf.get_date(date(2002,Feb,1)); <anchor id="first_kday_beforeconstruct-copy-destruct"/><computeroutput>first_kday_before</computeroutput> construct/copy/destructfirst_kday_before(day_of_week_type dow);<anchor id="id391469-bb"/><computeroutput>first_kday_before</computeroutput> public member functionsdate_type get_date(date_type start_day) const;Return next kday given. day_of_week_type day_of_week() const;Function template days_until_weekday3boost::date_time::days_until_weekdayCalculates the number of days until the next weekday. template<typename date_type, typename weekday_type>   date_type::duration_type   days_until_weekday(const date_type & d, const weekday_type & wd);DescriptionCalculates the number of days until the next weekday. If the date given falls on a Sunday and the given weekday is Tuesday the result will be 2 days Function template days_before_weekday3boost::date_time::days_before_weekdayCalculates the number of days since the previous weekday. template<typename date_type, typename weekday_type>   date_type::duration_type   days_before_weekday(const date_type & d, const weekday_type & wd);DescriptionCalculates the number of days since the previous weekday If the date given falls on a Sunday and the given weekday is Tuesday the result will be 5 days. The answer will be a positive number because Tuesday is 5 days before Sunday, not -5 days before. Function template next_weekday3boost::date_time::next_weekdayGenerates a date object representing the date of the following weekday from the given date. template<typename date_type, typename weekday_type>   date_type next_weekday(const date_type & d, const weekday_type & wd);DescriptionGenerates a date object representing the date of the following weekday from the given date. If the date given is 2004-May-9 (a Sunday) and the given weekday is Tuesday then the resulting date will be 2004-May-11. Function template previous_weekday3boost::date_time::previous_weekdayGenerates a date object representing the date of the previous weekday from the given date. template<typename date_type, typename weekday_type>   date_type previous_weekday(const date_type & d, const weekday_type & wd);DescriptionGenerates a date object representing the date of the previous weekday from the given date. If the date given is 2004-May-9 (a Sunday) and the given weekday is Tuesday then the resulting date will be 2004-May-4.
Header <<ulink url="../../boost/date_time/date_iterator.hpp">boost/date_time/date_iterator.hpp</ulink>>namespace boost {   namespace date_time {     template<typename date_type> class date_itr_base;     template<typename offset_functor, typename date_type> class date_itr;     // An iterator over dates with varying resolution (day, week, month, year, etc).     enum date_resolutions { day, week, months, year, decade, century,                             NumDateResolutions };   } }Class template date_itr_base3boost::date_time::date_itr_baseBase date iterator type. template<typename date_type> class date_itr_base { public:   // types   typedef date_type::duration_type duration_type;       typedef date_type                value_type;          typedef std::input_iterator_tag  iterator_category;   // construct/copy/destruct   date_itr_base(date_type);   ~date_itr_base();   // public member functions   date_itr_base & operator++() ;   date_itr_base & operator--() ;   virtual duration_type get_offset(const date_type &) const;   virtual duration_type get_neg_offset(const date_type &) const;   date_type operator *() ;   date_type * operator->() ;   bool operator<(const date_type &) ;   bool operator<=(const date_type &) ;   bool operator>(const date_type &) ;   bool operator>=(const date_type &) ;   bool operator==(const date_type &) ;   bool operator!=(const date_type &) ; };DescriptionThis class provides the skeleton for the creation of iterators. New and interesting interators can be created by plugging in a new function that derives the next value from the current state. generation of various types of -based information.Template Parametersdate_typeThe date_type is a concrete date_type. The date_type must define a duration_type and a calendar_type. <anchor id="date_itr_baseconstruct-copy-destruct"/><computeroutput>date_itr_base</computeroutput> construct/copy/destructdate_itr_base(date_type d);~date_itr_base();<anchor id="id405036-bb"/><computeroutput>date_itr_base</computeroutput> public member functionsdate_itr_base & operator++() ;date_itr_base & operator--() ;virtual duration_type get_offset(const date_type & current) const;virtual duration_type get_neg_offset(const date_type & current) const;date_type operator *() ;date_type * operator->() ;bool operator<(const date_type & d) ;bool operator<=(const date_type & d) ;bool operator>(const date_type & d) ;bool operator>=(const date_type & d) ;bool operator==(const date_type & d) ;bool operator!=(const date_type & d) ;Class template date_itr3boost::date_time::date_itrOverrides the base date iterator providing hook for functors. template<typename offset_functor, typename date_type> class date_itr : public boost::date_time::date_itr_base< date_type > { public:   // types   typedef date_type::duration_type duration_type;   // construct/copy/destruct   date_itr(date_type, int = 1);   // public member functions   // private member functions   virtual duration_type get_offset(const date_type &) const;   virtual duration_type get_neg_offset(const date_type &) const; };Description<anchor id="date_itrconstruct-copy-destruct"/><computeroutput>date_itr</computeroutput> construct/copy/destructdate_itr(date_type d, int factor = 1);<anchor id="id354910-bb"/><computeroutput>date_itr</computeroutput> public member functions<anchor id="id359787-bb"/><computeroutput>date_itr</computeroutput> private member functionsvirtual duration_type get_offset(const date_type & current) const;virtual duration_type get_neg_offset(const date_type & current) const;
Header <<ulink url="../../boost/date_time/date_names_put.hpp">boost/date_time/date_names_put.hpp</ulink>>namespace boost {   namespace date_time {     template<typename Config, typename charT = char,              typename OutputIterator = std::ostreambuf_iterator<charT> >     class date_names_put;     template<typename Config, typename charT = char,              typename OutputIterator = std::ostreambuf_iterator<charT> >     class all_date_names_put;   } }Class template date_names_put3boost::date_time::date_names_putOutput facet base class for gregorian dates. template<typename Config, typename charT = char,          typename OutputIterator = std::ostreambuf_iterator<charT> > class date_names_put { public:   // types   typedef OutputIterator             iter_type;            typedef Config::month_type         month_type;           typedef Config::month_enum         month_enum;           typedef Config::weekday_enum       weekday_enum;         typedef Config::special_value_enum special_value_enum;   typedef std::basic_string< charT > string_type;          // construct/copy/destruct   date_names_put();   // public member functions   void put_special_value(iter_type &, special_value_enum) const;   void put_month_short(iter_type &, month_enum) const;   void put_month_long(iter_type &, month_enum) const;   void put_weekday_short(iter_type &, weekday_enum) const;   void put_weekday_long(iter_type &, weekday_enum) const;   bool has_date_sep_chars() const;   void year_sep_char(iter_type &) const;   void month_sep_char(iter_type &) const;   void day_sep_char(iter_type &) const;   ymd_order_spec date_order() const;   month_format_spec month_format() const;   // protected member functions   virtual void do_put_month_short(iter_type &, month_enum) const;   virtual void do_put_month_long(iter_type &, month_enum) const;   virtual void do_put_special_value(iter_type &, special_value_enum) const;   virtual void do_put_weekday_short(iter_type &, weekday_enum) const;   virtual void do_put_weekday_long(iter_type &, weekday_enum) const;   virtual bool do_has_date_sep_chars() const;   virtual void do_year_sep_char(iter_type &) const;   virtual void do_month_sep_char(iter_type &) const;   virtual void do_day_sep_char(iter_type &) const;   virtual ymd_order_spec do_date_order() const;   virtual month_format_spec do_month_format() const;   void put_string(iter_type &, const charT *const) const;   void put_string(iter_type &, const string_type &) const;   static std::locale::id id; };DescriptionThis class is a base class for date facets used to localize the names of months and the names of days in the week.Requirements of Configdefine an enumeration month_enum that enumerates the months. The enumeration should be '1' based eg: Jan==1define as_short_string and as_long_string(see langer & kreft p334). <anchor id="date_names_putconstruct-copy-destruct"/><computeroutput>date_names_put</computeroutput> construct/copy/destructdate_names_put();<anchor id="id399644-bb"/><computeroutput>date_names_put</computeroutput> public member functionsvoid put_special_value(iter_type & oitr, special_value_enum sv) const;void put_month_short(iter_type & oitr, month_enum moy) const;void put_month_long(iter_type & oitr, month_enum moy) const;void put_weekday_short(iter_type & oitr, weekday_enum wd) const;void put_weekday_long(iter_type & oitr, weekday_enum wd) const;bool has_date_sep_chars() const;void year_sep_char(iter_type & oitr) const;void month_sep_char(iter_type & oitr) const;char between year-month void day_sep_char(iter_type & oitr) const;Char to separate month-day. ymd_order_spec date_order() const;Determines the order to put the date elements. month_format_spec month_format() const;Determines if month is displayed as integer, short or long string. <anchor id="id429109-bb"/><computeroutput>date_names_put</computeroutput> protected member functionsvirtual void do_put_month_short(iter_type & oitr, month_enum moy) const;Default facet implementation uses month_type defaults. virtual void do_put_month_long(iter_type & oitr, month_enum moy) const;Default facet implementation uses month_type defaults. virtual void do_put_special_value(iter_type & oitr, special_value_enum sv) const;Default facet implementation for special value types. virtual void do_put_weekday_short(iter_type & , weekday_enum ) const;virtual void do_put_weekday_long(iter_type & , weekday_enum ) const;virtual bool do_has_date_sep_chars() const;virtual void do_year_sep_char(iter_type & oitr) const;virtual void do_month_sep_char(iter_type & oitr) const;char between year-month virtual void do_day_sep_char(iter_type & oitr) const;Char to separate month-day. virtual ymd_order_spec do_date_order() const;Default for date order. virtual month_format_spec do_month_format() const;Default month format. void put_string(iter_type & oi, const charT *const s) const;void put_string(iter_type & oi, const string_type & s1) const;Class template all_date_names_put3boost::date_time::all_date_names_putAn date name output facet that takes an array of char* to define strings. template<typename Config, typename charT = char,          typename OutputIterator = std::ostreambuf_iterator<charT> > class all_date_names_put : public boost::date_time::date_names_put< Config, charT, OutputIterator > { public:   // types   typedef OutputIterator             iter_type;            typedef Config::month_enum         month_enum;           typedef Config::weekday_enum       weekday_enum;         typedef Config::special_value_enum special_value_enum;   // construct/copy/destruct   all_date_names_put(const charT *const, const charT *const,                      const charT *const, const charT *const,                      const charT *const, charT = '-',                      ymd_order_spec = ymd_order_iso,                      month_format_spec = month_as_short_string);   // public member functions   const charT *const * get_short_month_names() const;   const charT *const * get_long_month_names() const;   const charT *const * get_special_value_names() const;   const charT *const * get_short_weekday_names() const;   const charT *const * get_long_weekday_names() const;   // protected member functions   virtual void do_put_month_short(iter_type &, month_enum) const;   virtual void do_put_month_long(iter_type &, month_enum) const;   virtual void do_put_special_value(iter_type &, special_value_enum) const;   virtual void do_put_weekday_short(iter_type &, weekday_enum) const;   virtual void do_put_weekday_long(iter_type &, weekday_enum) const;   virtual void do_month_sep_char(iter_type &) const;   virtual void do_day_sep_char(iter_type &) const;   virtual ymd_order_spec do_date_order() const;   virtual month_format_spec do_month_format() const; };Description<anchor id="all_date_names_putconstruct-copy-destruct"/><computeroutput>all_date_names_put</computeroutput> construct/copy/destructall_date_names_put(const charT *const month_short_names,                    const charT *const month_long_names,                    const charT *const special_value_names,                    const charT *const weekday_short_names,                    const charT *const weekday_long_names,                    charT separator_char = '-',                    ymd_order_spec order_spec = ymd_order_iso,                    month_format_spec month_format = month_as_short_string);<anchor id="id330609-bb"/><computeroutput>all_date_names_put</computeroutput> public member functionsconst charT *const * get_short_month_names() const;const charT *const * get_long_month_names() const;const charT *const * get_special_value_names() const;const charT *const * get_short_weekday_names() const;const charT *const * get_long_weekday_names() const;<anchor id="id352064-bb"/><computeroutput>all_date_names_put</computeroutput> protected member functionsvirtual void do_put_month_short(iter_type & oitr, month_enum moy) const;Generic facet that takes array of chars. virtual void do_put_month_long(iter_type & oitr, month_enum moy) const;Long month names. virtual void do_put_special_value(iter_type & oitr, special_value_enum sv) const;Special values names. virtual void do_put_weekday_short(iter_type & oitr, weekday_enum wd) const;virtual void do_put_weekday_long(iter_type & oitr, weekday_enum wd) const;virtual void do_month_sep_char(iter_type & oitr) const;char between year-month virtual void do_day_sep_char(iter_type & oitr) const;Char to separate month-day. virtual ymd_order_spec do_date_order() const;Set the date ordering. virtual month_format_spec do_month_format() const;Set the date ordering.
Header <<ulink url="../../boost/date_time/dst_rules.hpp">boost/date_time/dst_rules.hpp</ulink>>Contains template class to provide static dst rule calculationsnamespace boost {   namespace date_time {     template<typename date_type_, typename time_duration_type_>     class dst_calculator;     template<typename date_type, typename time_duration_type,              typename dst_traits>     class dst_calc_engine;     template<typename date_type_, typename time_duration_type_,              unsigned int dst_start_offset_minutes = ,              short dst_length_minutes = >     class us_dst_rules;     template<typename date_type_, typename time_duration_type_>     class null_dst_rules;     enum time_is_dst_result { is_not_in_dst, is_in_dst, ambiguous,                               invalid_time_label };   } }Class template dst_calculator3boost::date_time::dst_calculatorDynamic class used to caluclate dst transition information. template<typename date_type_, typename time_duration_type_> class dst_calculator { public:   // types   typedef time_duration_type_ time_duration_type;   typedef date_type_          date_type;            // public static functions   time_is_dst_result   process_local_dst_start_day(const time_duration_type &, unsigned int, long) ;   time_is_dst_result   process_local_dst_end_day(const time_duration_type &, unsigned int, long) ;   time_is_dst_result   local_is_dst(const date_type &, const time_duration_type &,                const date_type &, unsigned int, const date_type &,                unsigned int, long) ; };Description<anchor id="id419715-bb"/><computeroutput>dst_calculator</computeroutput> public static functionstime_is_dst_result process_local_dst_start_day(const time_duration_type & time_of_day,                             unsigned int dst_start_offset_minutes,                             long dst_length_minutes) ;Check the local time offset when on dst start day. On this dst transition, the time label between the transition boundary and the boudary + the offset are invalid times. If before the boundary then still not in dst. Parametersdst_length_minutesNumber of minutes to adjust clock forward dst_start_offset_minutesLocal day offset for start of dst time_of_dayTime offset in the day for the local time time_is_dst_result process_local_dst_end_day(const time_duration_type & time_of_day,                           unsigned int dst_end_offset_minutes,                           long dst_length_minutes) ;Check the local time offset when on the last day of dst. This is the calculation for the DST end day. On that day times prior to the conversion time - dst_length (1 am in US) are still in dst. Times between the above and the switch time are ambiguous. Times after the start_offset are not in dst. Parametersdst_end_offset_minutesLocal time of day for end of dst time_of_dayTime offset in the day for the local time time_is_dst_result local_is_dst(const date_type & current_day,              const time_duration_type & time_of_day,              const date_type & dst_start_day,              unsigned int dst_start_offset_minutes,              const date_type & dst_end_day,              unsigned int dst_end_offset_minutes, long dst_length_minutes) ;Calculates if the given local time is dst or not. Determines if the time is really in DST or not. Also checks for invalid and ambiguous. Parameterscurrent_dayThe day to check for dst dst_end_dayEnding day of dst for the given locality dst_end_offset_minutesOffset within day given in dst for dst boundary (eg 120 for US which is 02:00:00) dst_length_minutesLength of dst adjusment (eg: 60 for US) dst_start_dayStarting day of dst for the given locality dst_start_offset_minutesOffset within day for dst boundary (eg 120 for US which is 02:00:00) time_of_dayTime offset within the day to check Class template dst_calc_engine3boost::date_time::dst_calc_engineCompile-time configurable daylight savings time calculation engine. template<typename date_type, typename time_duration_type, typename dst_traits> class dst_calc_engine { public:   // types   typedef date_type::year_type                            year_type;       typedef date_type::calendar_type                        calendar_type;   typedef dst_calculator< date_type, time_duration_type > dstcalc;         // public static functions   time_is_dst_result   local_is_dst(const date_type &, const time_duration_type &) ;   bool is_dst_boundary_day(date_type) ;   time_duration_type dst_offset() ;   date_type local_dst_start_day(year_type) ;   date_type local_dst_end_day(year_type) ; };Description<anchor id="id389178-bb"/><computeroutput>dst_calc_engine</computeroutput> public static functionstime_is_dst_result local_is_dst(const date_type & d, const time_duration_type & td) ;Calculates if the given local time is dst or not. Determines if the time is really in DST or not. Also checks for invalid and ambiguous. bool is_dst_boundary_day(date_type d) ;time_duration_type dst_offset() ;The time of day for the dst transition (eg: typically 01:00:00 or 02:00:00). date_type local_dst_start_day(year_type year) ;date_type local_dst_end_day(year_type year) ;Class template us_dst_rules3boost::date_time::us_dst_rulesDepricated: Class to calculate dst boundaries for US time zones. template<typename date_type_, typename time_duration_type_,          unsigned int dst_start_offset_minutes = ,          short dst_length_minutes = > class us_dst_rules { public:   // types   typedef time_duration_type_                             time_duration_type;   typedef date_type_                                      date_type;            typedef date_type::year_type                            year_type;            typedef date_type::calendar_type                        calendar_type;        typedef date_time::last_kday_of_month< date_type >      lkday;                typedef date_time::first_kday_of_month< date_type >     fkday;                typedef dst_calculator< date_type, time_duration_type > dstcalc;              // public static functions   time_is_dst_result   local_is_dst(const date_type &, const time_duration_type &) ;   bool is_dst_boundary_day(date_type) ;   date_type local_dst_start_day(year_type) ;   date_type local_dst_end_day(year_type) ;   time_duration_type dst_offset() ; };Description<anchor id="id386155-bb"/><computeroutput>us_dst_rules</computeroutput> public static functionstime_is_dst_result local_is_dst(const date_type & d, const time_duration_type & td) ;Calculates if the given local time is dst or not. Determines if the time is really in DST or not. Also checks for invalid and ambiguous. bool is_dst_boundary_day(date_type d) ;date_type local_dst_start_day(year_type year) ;date_type local_dst_end_day(year_type year) ;time_duration_type dst_offset() ;Class template null_dst_rules3boost::date_time::null_dst_rulesUsed for local time adjustments in places that don't use dst. template<typename date_type_, typename time_duration_type_> class null_dst_rules { public:   // types   typedef time_duration_type_ time_duration_type;   typedef date_type_          date_type;            // public static functions   time_is_dst_result   local_is_dst(const date_type &, const time_duration_type &) ;   time_is_dst_result   utc_is_dst(const date_type &, const time_duration_type &) ;   bool is_dst_boundary_day(date_type) ;   time_duration_type dst_offset() ; };Description<anchor id="id300974-bb"/><computeroutput>null_dst_rules</computeroutput> public static functionstime_is_dst_result local_is_dst(const date_type & , const time_duration_type & ) ;Calculates if the given local time is dst or not. time_is_dst_result utc_is_dst(const date_type & , const time_duration_type & ) ;Calculates if the given utc time is in dst. bool is_dst_boundary_day(date_type d) ;time_duration_type dst_offset() ;
Header <<ulink url="../../boost/date_time/dst_transition_generators.hpp">boost/date_time/dst_transition_generators.hpp</ulink>>namespace boost {   namespace date_time {     template<typename date_type> class dst_day_calc_rule;     template<typename spec> class day_calc_dst_rule;   } }Class template dst_day_calc_rule3boost::date_time::dst_day_calc_ruleDefines base interface for calculating start and end date of daylight savings. template<typename date_type> class dst_day_calc_rule { public:   // types   typedef date_type::year_type year_type;   // construct/copy/destruct   ~dst_day_calc_rule();   // public member functions   virtual date_type start_day(year_type) const;   virtual date_type end_day(year_type) const; };Description<anchor id="dst_day_calc_ruleconstruct-copy-destruct"/><computeroutput>dst_day_calc_rule</computeroutput> construct/copy/destruct~dst_day_calc_rule();<anchor id="id425419-bb"/><computeroutput>dst_day_calc_rule</computeroutput> public member functionsvirtual date_type start_day(year_type y) const;virtual date_type end_day(year_type y) const;Class template day_calc_dst_rule3boost::date_time::day_calc_dst_ruleCanonical form for a class that provides day rule calculation. template<typename spec> class day_calc_dst_rule : : public boost::date_time::dst_day_calc_rule< spec::date_type > { public:   // types   typedef spec::date_type      date_type;    typedef date_type::year_type year_type;    typedef spec::start_rule     start_rule;   typedef spec::end_rule       end_rule;     // construct/copy/destruct   day_calc_dst_rule(start_rule, end_rule);   // public member functions   virtual date_type start_day(year_type) const;   virtual date_type end_day(year_type) const; };DescriptionThis class is used to generate specific sets of dst rules<anchor id="day_calc_dst_ruleconstruct-copy-destruct"/><computeroutput>day_calc_dst_rule</computeroutput> construct/copy/destructday_calc_dst_rule(start_rule dst_start, end_rule dst_end);<anchor id="id396452-bb"/><computeroutput>day_calc_dst_rule</computeroutput> public member functionsvirtual date_type start_day(year_type y) const;virtual date_type end_day(year_type y) const;
Header <<ulink url="../../boost/date_time/filetime_functions.hpp">boost/date_time/filetime_functions.hpp</ulink>>Function(s) for converting between a FILETIME structure and a time object. This file is only available on systems that have BOOST_HAS_FTIME defined.namespace boost {   namespace date_time {     template<typename time_type> time_type time_from_ftime(const FILETIME &);   } }Function template time_from_ftime3boost::date_time::time_from_ftimeCreate a time object from an initialized FILETIME struct. template<typename time_type> time_type time_from_ftime(const FILETIME & ft);DescriptionCreate a time object from an initialized FILETIME struct. A FILETIME struct holds 100-nanosecond units (0.0000001). When built with microsecond resolution the FILETIME's sub second value will be truncated. Nanosecond resolution has no truncation.
Header <<ulink url="../../boost/date_time/gregorian_calendar.hpp">boost/date_time/gregorian_calendar.hpp</ulink>>namespace boost {   namespace date_time {     template<typename ymd_type_, typename date_int_type_>     class gregorian_calendar_base;   } }Class template gregorian_calendar_base3boost::date_time::gregorian_calendar_baseAn implementation of the Gregorian calendar. template<typename ymd_type_, typename date_int_type_> class gregorian_calendar_base { public:   // types   typedef ymd_type_            ymd_type;      // define a type a date split into components   typedef ymd_type::month_type month_type;    // define a type for representing months   typedef ymd_type::day_type   day_type;      // define a type for representing days   typedef ymd_type::year_type  year_type;     // Type to hold a stand alone year value (eg: 2002).   typedef date_int_type_       date_int_type; // Define the integer type to use for internal calculations.   // public static functions   unsigned short day_of_week(const ymd_type &) ;   int week_number(const ymd_type &) ;   date_int_type day_number(const ymd_type &) ;   date_int_type julian_day_number(const ymd_type &) ;   long modjulian_day_number(const ymd_type &) ;   ymd_type from_day_number(date_int_type) ;   ymd_type from_julian_day_number(date_int_type) ;   ymd_type from_modjulian_day_number(long) ;   bool is_leap_year(year_type) ;   unsigned short end_of_month_day(year_type, month_type) ;   ymd_type epoch() ;   unsigned short days_in_week() ; };DescriptionThis is a parameterized implementation of a proleptic Gregorian Calendar that can be used in the creation of date systems or just to perform calculations. All the methods of this class are static functions, so the intent is to never create instances of this class. <anchor id="id423726-bb"/><computeroutput>gregorian_calendar_base</computeroutput> public static functionsunsigned short day_of_week(const ymd_type & ymd) ;int week_number(const ymd_type & ymd) ;date_int_type day_number(const ymd_type & ymd) ;date_int_type julian_day_number(const ymd_type & ymd) ;long modjulian_day_number(const ymd_type & ymd) ;ymd_type from_day_number(date_int_type ) ;ymd_type from_julian_day_number(date_int_type ) ;ymd_type from_modjulian_day_number(long ) ;bool is_leap_year(year_type ) ;unsigned short end_of_month_day(year_type y, month_type m) ;ymd_type epoch() ;unsigned short days_in_week() ;
Header <<ulink url="../../boost/date_time/int_adapter.hpp">boost/date_time/int_adapter.hpp</ulink>>namespace boost {   namespace date_time {     template<typename int_type_> class int_adapter;     template<typename charT, typename traits, typename int_type>       std::basic_ostream< charT, traits > &       operator<<(std::basic_ostream< charT, traits > &,                  const int_adapter< int_type > &);   } }Class template int_adapter3boost::date_time::int_adapterAdapter to create integer types with +-infinity, and not a value. template<typename int_type_> class int_adapter { public:   // types   typedef int_type_ int_type;   // construct/copy/destruct   int_adapter(int_type);   // public member functions   bool is_infinity() const;   bool is_pos_infinity() const;   bool is_neg_infinity() const;   bool is_nan() const;   bool is_special() const;   bool operator==(const int_adapter &) const;   bool operator==(const int &) const;   bool operator!=(const int_adapter &) const;   bool operator!=(const int &) const;   bool operator<(const int_adapter &) const;   bool operator<(const int &) const;   bool operator>(const int_adapter &) const;   int_type as_number() const;   special_values as_special() const;   template<typename rhs_type>     int_adapter operator+(const int_adapter< rhs_type > &) const;   int_adapter operator+(const int_type) const;   template<typename rhs_type>     int_adapter operator-(const int_adapter< rhs_type > &) const;   int_adapter operator-(const int_type) const;   int_adapter operator *(const int_adapter &) const;   int_adapter operator *(const int) const;   int_adapter operator/(const int_adapter &) const;   int_adapter operator/(const int) const;   int_adapter operator%(const int_adapter &) const;   int_adapter operator%(const int) const;   // public static functions   bool has_infinity() ;   const int_adapter pos_infinity() ;   const int_adapter neg_infinity() ;   const int_adapter not_a_number() ;   int_adapter max BOOST_PREVENT_MACRO_SUBSTITUTION() ;   int_adapter min BOOST_PREVENT_MACRO_SUBSTITUTION() ;   int_adapter from_special(special_values) ;   bool is_inf(int_type) ;   bool is_neg_inf(int_type) ;   bool is_pos_inf(int_type) ;   bool is_not_a_number(int_type) ;   special_values to_special(int_type) ;   int_type maxcount() ;   // private member functions   int compare(const int_adapter &) const;   int_adapter mult_div_specials(const int_adapter &) const;   int_adap