Broad Network


String Format of C++ Time

Date and Time in C++ Simplified - Part 4

Forward: In this part of the series, we look at the way C++ displays its time as a string.

By: Chrysanthus Date Published: 25 Aug 2012

Introduction

This is part 4 of my series, Date and Time in C++, Simplified. In this part of the series, we look at the way C++ displays its time as a string. The discussion refers to the features in the ctime healer file.

Holding a C++ Time
C++ time is held either in a struct tm object or a time_t object. We do not need to know the nature of the time_t object, but we need to know how to use it. We know the nature of the struct tm object (see a previous part of this series).

Inputting Time
If time is to be inputted by the user then the input time should be held by a struct tm object. A summary of the nature of the struct tm object is:

int tm_sec; // seconds after the minute — [0, 59]
int tm_min; // minutes after the hour — [0, 59]
int tm_hour; // hours since midnight — [0, 23]
int tm_mday; // day of the month — [1, 31]
int tm_mon; // months since January — [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday — [0, 6]
int tm_yday; // days since January 1 — [0, 365]
int tm_isdst; // Daylight Saving Time flag

As you can see, most of the values begin from zero and extend above 10. The interest here is that some of the values (e.g. minutes) can consist of 1, 2 or even 3 digits. When inputting any of these values into the struct tm object, if it is 1 digit, you can type just the 1 digit or precede it with leading zero. Internally, the struct tm object will remove any leading zero from its values.

Outputting Time
A typical string time output is,

        Sun Sep 16 01:03:52 1973

If your time is held in a struct tm object then the asctime function can be used to convert it into a string (see one of the previous parts of this series). On the other hand, if your time is held in a time_t object then the ctime function can be used to convert it into a string (see one of the previous parts of this series).

Format of String Output
The output from either of the functions above begins with the week-day in three letters. Next, you have a space and then the month in three letters. A space again and then the day of the month in a 2-digit integer. Then, a space and then the hour in a 2 digit integer. Next, a colon and then the minutes in a 2-digit integer. Then, a colon again and then the seconds in a 2-digit integer. Finally, a space and then the correct 4-digit year. If a value is a single digit, then, it is preceded by a single zero.

That is the format in which you get a C++ string time (date and time).

That is it for this part of the series. Let us take a break and continue in the next part.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem

Comments

Become the Writer's Fan
Send the Writer a Message