portability/time.hpp
Utilities for manipulating times

Introduction

Simplified access to representations of time and conversions between them. The motivation for this package is that the low-level system calls for accessing time are ugly and therefore potentially error-prone. I hope that this interface is much simpler and therefore easier to use and more likely to yield first-time right programs.

Time is represented as the built-in integer type time_t - this is the standard representation of system time in computerland and represents the number of seconds since midnight 1 Jan 1970, believe it or not.

Functions are provided here for converting to and from more human-comprehendable forms.

Creating times

These functions create the time_t type from either the current time or a specified time. See also file_system.hpp for functions to get timestamps for files.

time_t time_now(void);

This function gets the integer representing the time now.

time_t localtime_create(int year, int month, int day, int hour, int minute, int second);

This function gets the integer representing the requested time. Note that the parameters use normal human conventions, so the year would be something like 2002, the month is a number from 1-12 with 1=January, the day is the day of the month in the range 1-31, the hour uses the 24-hour clock so has the range 0-23 and the minutes and seconds are in the range 0-59.

Human times

There is a set of functions that allow the extraction of human-centric forms of the machine representation. These form the converse of the localtime_create() function above. It is also possible to extract extra information such as the day of the week.

int localtime_year(time_t);

Extracts the year e.g. 1962.

int localtime_month(time_t);

Extracts the month, numbered 1-12 e.g. August = 8.

int localtime_day(time_t);

Extracts the day of the month numbered 1-31 e.g. 29.

int localtime_hour(time_t);

Extracts the hour of day numbered 0-23.

int localtime_minute(time_t);

Extracts the minute past the hour numbered 0-59.

int localtime_second(time_t);

Extracts the second past the minute numbered 0-59.

int localtime_weekday(time_t);

Extracts the day of the week numbered 0-6 with 0=Sunday.

int localtime_yearday(time_t);

Extracts the number of days into the year. January 1 = 0.

Printing times

std::string localtime_string(time_t);

Converts the integer representation of time to a human-readable form for saving to a file or printing.