Share the ideas and thoughts, become united ...

Monday, August 9, 2010

PHP Date Tips & Usage

We all need the current date now and then. Today I will review some of the usage of PHP date functions.

$array = getdate();
  • There are many ways to get the current date. Probably the easiest one is getdate() function.
  • The return type of the getdate() is an array. So the values of the current time is mapped into a (key => value) pair. i,e for every value there will be a mapped key.
  • Useful Keys are
    • minutes  - returns minutes
    • seconds  - returns seconds
    • hours    - returns hours
    • mday     - returns day of the month (no of the day of current month) (between 1-31)
    • yday     - returns day of the year (between 1-365)
    • month    - textual representation of the current month
    • mon      - returns the current month number (between 1-12)
    • year     - returns the current year
  • e,g -
$today = getdate();
echo $today['mon'] . '/' . $today['mday'] . '/' . $today['year'];     // outputs --> mm/dd/yyyy
Another way of getting the date is the date function itself.


$string = date($format);
  • The format is a string which defines the format of the date
  • The useful formats are -
    • d   - the day of the month (between 1-31)
    • D  - short textual representation of the day of the month (e,g Sun, Mon etc.)
    • t    -  no of days in that month (e,g 28 for feb, 31 for jan etc.)
    • m  - the month of the year (between 1-12)
    • M - short textual representation of the month of the year (e,g Jan, Feb etc.)
    • y  - two digit representation of the year (e,g 99)
    • Y - four digit representation of the year (e,g 2099)
    • L - 1 if this year is a leap year, 0 otherwise
    • h  - hours (in 12 hrs format)
    • H - hours (in 24 hrs format)
    • i - minutes
    • s - seconds
  • e,g -
echo date("D, d-M, Y : H:i:s");   // we are telling the php parser that we will use short textual day name first then the actual day number of that month. Then we will show the short name of the month with a dash in between the day and the month. Lastly we will show the year in full 4 digit format. the last part shows the time. We used the H for showing the time in 24 hrs format i and s for minutes and seconds. We have to add 'a' or 'A' to get the AM/PM display in the format.
 If you have any suggestion or question, please feel free to drop a comment.

No comments:

Post a Comment