Team LiB
Previous Section Next Section

Formatting Date and Time Values

Date and time values are always quite difficult to deal with, and not only from a representation point of view. Because the Universe refuses to work on multiples of ten, and the measurement of time that we take for granted is not exactly that accurate, calculating the difference between two dates is one problem that all developers fear (and eventually face with varying degrees of success).

Even though the basic units of time used throughout the world are pretty much the same, the way they are displayed varies greatly. For example, most European countries (with the notable exception of the U.K.) format dates using a day/month/year notation (for example: 23/2/1976 to indicate February 23, 1976). On the other hand, English-speaking countries format dates using a month/day/year notation, so that February 23, 1976, is written as 2/23/1976.

The confusion is great, and so is the difficulty in formatting dates according to each user's preferences. Luckily, PHP provides a very useful function, called strftime(), that can be used to represent a date/time value as a string according to the locale settings of LC_TIME.

The strftime function takes two parameters:

strftime ($format[, $timestamp]);

The optional $timestamp parameter provides the Unix-timestamp value that must be converted to a string. If it is not provided, then strftime() uses the current system time. The $format parameter contains a set of specifiers that determine how the date/time value will be represented.

For example:


      setlocale (LC_TIME, 'en_US');
      echo strftime ('%A, %B %d %G, %T');
      echo "\n";
      setlocale (LC_TIME, 'it_IT');
      echo strftime ('%A, %d %B %G, %T');
      echo "\n";


outputs the current date and time in U.S. English first and then in Italian:

Tuesday, April 15 2003, 07:52:21
martedì, 15 aprile 2003, 07:52:21

    Team LiB
    Previous Section Next Section