devxlogo

Minimize Date and Time Display Drudgery

Minimize Date and Time Display Drudgery

any moons ago, I presented C++’s basic time and date facilities. At that time, however, I didn’t demonstrate how to format and customize the date and time. Such customizations may be needed when you localize an application, for example. Although internationalization and localization are notoriously complex, with some help from ‘s function strftime(), you can eliminate much of this drudgery?at least as far as the time and date are concerned.


How do you format the date and time in an easy and portable manner?


Use the strftime() library function.

Time for a Change
It’s hard to imagine a large-scale application that doesn’t rely on date and time calculations. In most cases, a crude representation of the system’s time (e.g., time_t) is used. However, when the date and time are presented in a human readable format, customization and formatting are necessary. In the United States, the accepted date format is MMDDYYYY. However, in many other countries the day precedes the month, as in 31/12/2007. Similarly, the common time format in the UK is based on a 12 hour clock, e.g., 6:30 PM, whereas in other countries a 24-hour clock is used instead i.e., 18:30. These locale-specific differences, along with text formatting, are all handled by the strftime() function declared in . strftime() takes a format string to compose a date and time string:

size_t strftime(char *s,                 size_t maxsz,                 const char *fmt,                 const struct tm *ptm);

The first parameter is the address of a memory buffer into which the resulting date and time string is written. The maxsz parameter specifies the maximum number of characters that can be written to s, excluding the terminating

devx-admin

Share the Post: