Rogério Lino

Web development and tips

PHP: Easy SQL Date Time Formatting

SQL to Human:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* 
 * date
 */
$format = 'm/d/Y'; // en-US
// $format = 'd/m/Y'; // pt-BR
$date = '2012-02-01';
echo date($format, strtotime($date));


/* 
 * datetime
 */
$format .= ' H:i:s';
$datetime = '2012-02-01 11:33:59';
echo date($format, strtotime($datetime));

Human to SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* 
 * date
 */
$sqlFormat = 'Y-m-d';
$date = '02/01/2012';

// en-US
echo date($sqlFormat, strtotime($date));
// pt-BR
echo join('-', array_reverse(explode('/', $date)));


/* 
 * datetime
 */
$sqlFormat = 'Y-m-d H:i:s';

// en-US
$datetime = '02/01/2012 11:33:59';
echo date($sqlFormat, strtotime($datetime));

// pt-BR
$datetime = '01/02/2012 11:33:59';
$datetime = explode(' ', $datetime);
$date = join('-', array_reverse(explode('/', $datetime[0])));
echo $date . ' ' . $datetime[1];

Reference:

strtotime The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

date Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

explode Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

array_reverse Takes an input array and returns a new array with the order of the elements reversed.

join / implode Join array elements with a glue string.

Comments