Brainsofsteel header

Handling time and dates in PHP

Subject: tutorials

Description: How to work with timestamps in PHP

Posted by David Caldwell on 15/11/15 at 20:34

In MySql databases it is common practise to store the date and time a record was created. The variable type is called a timestamp.

 

DATE

timestamp

   

No

CURRENT_TIMESTAMP

A timestamp in structure view

Below is an example of a timestamp and how it is structured.

  • “2015-11-15 20:34:35”
  • Year-Month-Day Hour-Minute-Second
  • Y-M-D H-M-S

A timestamp isn't easy to read by humans so we will need to format it.

In the following code example we use the PHP function strtotime() to convert our textual timestamp into a Unix timestamp.

Now that we have a Unix timestamp we can utilise the date() function.

date(desired format, your timestamp)

to format a timestamp into a UK format we  would use date("d/m/y”, your timestamp);

	<?
		$timestamp = "2015-11-15 20:34:35";
		$date = strtotime($timestamp);			
		$formatedDate = date("l d/m/Y",$date);
		$hourMin = date('H:i',$date);
		echo $formatedDate;
		echo '<br />';
		echo $hourMin;
	?>

The above code would output

Sunday 15/11/2015
20:34

Retrieving a timestamp from a MySQL database.

<?php
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
 DATABASE_NAME);
$sql =  mysqli_query($dbc, "SELECT 'date' FROM `table`") or die("Error: ".mysqli_error($dbc));
while($row=mysqli_fetch_array($sql))
{
	$xDate = strtotime($row['DATE']);			
	$yDate = date("d/m/y",$xDate);
	$hourMin = date('H:i',$xDate);
}
?>
Keywords: