1 // io_ex1.cpp ----------------------------------------------------------//
2
3 // Copyright 2010 Howard Hinnant
4 // Copyright 2010 Vicente J. Botet Escriba
5
6 // Distributed under the Boost Software License, Version 1.0.
7 // See http://www.boost.org/LICENSE_1_0.txt
8
9 /*
10 This code was adapted by Vicente J. Botet Escriba from Hinnant's html documentation.
11 Many thanks to Howard for making his code available under the Boost license.
12
13 */
14
15 #include <boost/chrono/chrono_io.hpp>
16 #include <ostream>
17 #include <iostream>
18
19 // format duration as [-]d/hh::mm::ss.cc
20 template <class CharT, class Traits, class Rep, class Period>
21 std::basic_ostream<CharT, Traits>&
display(std::basic_ostream<CharT,Traits> & os,boost::chrono::duration<Rep,Period> d)22 display(std::basic_ostream<CharT, Traits>& os,
23 boost::chrono::duration<Rep, Period> d)
24 {
25 using std::cout;
26 using namespace boost;
27 using namespace boost::chrono;
28
29 typedef duration<long long, ratio<86400> > days;
30 typedef duration<long long, centi> centiseconds;
31
32 // if negative, print negative sign and negate
33 if (d < duration<Rep, Period>(0))
34 {
35 d = -d;
36 os << '-';
37 }
38 // round d to nearest centiseconds, to even on tie
39 centiseconds cs = duration_cast<centiseconds>(d);
40 if (d - cs > milliseconds(5)
41 || (d - cs == milliseconds(5) && cs.count() & 1))
42 ++cs;
43 // separate seconds from centiseconds
44 seconds s = duration_cast<seconds>(cs);
45 cs -= s;
46 // separate minutes from seconds
47 minutes m = duration_cast<minutes>(s);
48 s -= m;
49 // separate hours from minutes
50 hours h = duration_cast<hours>(m);
51 m -= h;
52 // separate days from hours
53 days dy = duration_cast<days>(h);
54 h -= dy;
55 // print d/hh:mm:ss.cc
56 os << dy.count() << '/';
57 if (h < hours(10))
58 os << '0';
59 os << h.count() << ':';
60 if (m < minutes(10))
61 os << '0';
62 os << m.count() << ':';
63 if (s < seconds(10))
64 os << '0';
65 os << s.count() << '.';
66 if (cs < centiseconds(10))
67 os << '0';
68 os << cs.count();
69 return os;
70 }
71
main()72 int main()
73 {
74 using std::cout;
75 using namespace boost;
76 using namespace boost::chrono;
77
78 #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY
79 display(cout, steady_clock::now().time_since_epoch()
80 + duration<long, mega>(1)) << '\n';
81 #endif
82 display(cout, -milliseconds(6)) << '\n';
83 display(cout, duration<long, mega>(1)) << '\n';
84 display(cout, -duration<long, mega>(1)) << '\n';
85 }
86
87 //~ 12/06:03:22.95
88 //~ -0/00:00:00.01
89 //~ 11/13:46:40.00
90 //~ -11/13:46:40.00
91