Brainsofsteel header

Handling time and dates in PHP

Subject: tutorials

Description: How to work with timestamps in PHP


submit to reddit 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:




comments powered by Disqus

 Subscribe in a reader

RSS Feed

Latest Posts

17/11/15
How to Create a Time Sheet in Excel
15/11/15
Handling time and dates in PHP
03/02/15
How to Enhance Photographs with the Gimp
25/01/15
How to Cook Pigeon
25/01/15
Telling the Time
24/01/15
An Old Travel Card
10/09/14
How to Learn the Nine Times Table
09/08/14
How to Calculate the Direction between two Points
01/08/14
Making a large Google XML sitemap
18/05/14
How to make a pyramid