Posix Time

| Home | Libraries | People | FAQ | More

### Posix Time

## Posix Time System

Introduction -- Usage Examples

### Introduction

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

### Usage Examples

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

#### Ptime Class

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

### Introduction

The class boost::posix_time::ptime is the primary interface for time point manipulation. In general, the ptime class is immutable once constructed although it does allow assignment.

Class ptime is dependent on gregorian::date for the interface to the date portion of a time point.

Other techniques for creating times include time iterators.

### Header

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

### Construction

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

### Construct from String

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

### Construct from Clock

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

### Construct using Conversion Functions

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

### Accessors

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

### Conversion to String

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

### Operators

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

top

#### Time Duration

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

### Introduction

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

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

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

As an example:

          using namespace boost::posix_time;

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

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

### Header

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

### Construction

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

### Count Based Construction

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

### Construct from String

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

### Accessors

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

### Conversion To String

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

### Operators

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

top

#### Time Period

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

### Introduction

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

The time periods example provides an example of using time periods.

### Header

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

### Construction

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

### Accessors

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

### Conversion To String

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

### Operators

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

top

#### Time Iterators

Introduction -- Header -- Overview -- Operators

### Introduction

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

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

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

### Header

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

### Overview

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

### Operators

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

top

#### Local Time Adjustment

Introduction -- Header -- Overview

### Introduction

A frequent problem in time representation is the conversion between various local time systems. In general this is accomplished by using a reference time system. The reference time system is typically UTC.

Since the posix_time system does no internal time adjustment it can be used to represent both local times and UTC times. However, the user is currently left to handle conversions and time zone knowledge explicitly.

The library offers two different ways to perform UTC to local conversions. The first is using the time zone settings of the computer. This is a useful solution for converting a UTC time for a user machine. This approach depends on the ctime API and will provide incorrect results if the environment is set incorrectly. The other approach allows conversion from any zone to UTC and back independent of the settings of the time zone settings of the computer. The local utc conversion example demonstrates both of these techniques.

### Header

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

### Overview

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

top

| Copyright © 2001-2004 CrystalClear Software, Inc