|
Dates in PHP: Part 1Posted: May 10, 2007 Last modified: Apr 27, 2018Dates are passed around a lot in web applications, so it's a good idea to be able to handle them properly. Thankfully, PHP provides many built-in functions to help with this. In this article, I look at how to display & format dates in PHP. Very often, one my scripts will need to display a date in a certain format. I find that the best function for formatting dates is the As an example, the following code takes the current date and displays it in the format "1st of January 1970": print date("jS \of F Y"); The format parameter is the string "jS of F Y", which contains characters which the function understands have special meanings. Stepping through that string, the function knows to replace "j" with the day of the month (with leading zeros), "S" with the ordinal suffix for the day of month (such as 1st), "F" with the full month name, and "Y" with the full, four digit year. Notice that the function did not convert "\of" into anything else. This is because the special character "o" was escaped using a backslash and the character "f" does not have a special meaning for the function. The manual page linked to above contains a table of the special characters accepted by the function. The date function can also display information about the time of day. To print the time in the format "18:30:22" (hours:minutes:seconds) for a given timestamp, you would use: print date("H:i:s", $timestamp); The $timestamp parameter might be obtained or passed to you from another part of the application, but you can synthesize your own using the As of version 5.1.1, PHP provides constants that can be used for the format parameter that will make your life a little easier. For example, the constant PHP provides an identical function, |