Online Shopping : Computers : Programming : Languages : PHP : Function Libraries : Date and Time

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

24 of 37 people (65%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How to format a date for MySQL

Aug 22nd, 2003 03:37
Nick Nettleton, Mike Scott, D Goosen,


MySQL's default DATE field format is YYYY-MM-DD; however, when 
using getdate(), accessing the 'mon' variable of the resulting array 
doesn't zero-substitute (i.e., it returns 7, not 07, etc.).
Here's one way to format the date for MySQL:
#?php
// getdate function, taken as array to access vars
$today = getdate();
$year = $today['year'];
$month = $today['mon'];
$mday = $today['mday'];
// zero-substitutes MONTH if less than 10, concatenates 'mon' var 
if ($month < 10) {
$month = "0";
$month .= $today['mon'];
}
// concatenates date in MySQL date format YYYY-MM-DD
$date = $year;
$date .= "-";
$date .= $month;
$date .= "-";
$date .= $mday;
print($date);
#?>
------------------
There's a much simpler solution that only takes one line:-
<?php
  print strftime( '%Y-%m-%d' ) ;
?>
In addition, if you want to format numbers in output, e.g. to add 
leading zeroes, use sprintf. For example:
<?php
  $today = getdate ;
  print sprintf( '%4d-%02d-%02d', $today['year'], $today['mon'], $today
['mday'] ) ;
?>
MikeS.
--------------------
// even faster:
$date = date( "Ymd" ) ;
// mysql accepts date/time input in the format yyyymmddhhiiss
// nick