4 Time points, duration, and literals

 

This chapter covers

  • Using std::chrono time points and durations
  • Using ratios
  • Using literal suffixes
  • Using the overloaded operator/ to create dates
  • Input and output of time points and durations
  • Using different time zones

In this chapter, we will make a short program to create a countdown to an event. To do this, we will use time points and durations from the chrono header. This feature was introduced in C++11, and although the essence has remained the same, several useful additions have been made over time. Howard Hinnant is the main author and designer of this feature. In his Meeting C++ talk in 2019, he gave a lot of background to its design (https://www.youtube.com/watch?v=adSAN282YIw). As we use chrono, we will learn several important idioms and approaches applicable to many other situations.

We will build a simple countdown in the first section and then dig deeper into the types we used. We will discover how to use the ratio templates so that we can understand durations. We’ll then learn how to read dates in so we can count down to any event and print out countdowns in various units. We will learn about literal suffixes to specify days, months, and so on and why they are useful. We will also encounter the idea of requirements and touch on concepts. Having covered these newer C++ features, we’ll finish with a countdown using a zoned time.

4.1 How long until the last day of the year?

4.2 Understanding durations in detail

4.2.1 Ratios

4.2.2 Durations

4.2.3 Literal suffixes and operator / for readable code

4.2.4 Requirements and concepts

4.2.5 How many days until the last day of the year?

4.2.6 Using last to find how long to payday

4.2.7 Writing testable code

4.3 Input, output, and formatting

4.3.1 Parsing a date

4.3.2 Formatting time points and durations