Page 1 of 1

Extracting time only from mysql datetime feild?

Posted: Mon Oct 10, 2005 3:27 am
by robster
Hi all,

I have this piece of code for getting a mysql date and making it look pretty (real words) in php, donated by a kind soul in this forum:

Code: Select all

function convert_date_time($date)
	{
		$date = "$date";
		$parts = explode( "-", $date );
		$timestamp = mktime( 0, 0, 0, $parts[1], $parts[2], $parts[0] );
		$return_date = date( "l, d M Y", $timestamp );
		return ($return_date);
	}
That is fine with a mysql date format (0000-00-00);


I now have a mysql datetime format (0000-00-00 00:00:00) and want to do the same thing except only extract the time from the data. I've been playing around but to no luck :(

I'm wondering if somebody could help out? This is what I have so far, and it fails, it shows 12:00 all the time.

Code: Select all

function convert_date_time($date)
	{
		$date = "$date";
		$parts = explode( "-", $date );
		$timestamp = mktime( 0, 0, 0, $parts[1], $parts[2], $parts[0] );
		$return_date = date( "g:i", $timestamp );
		return ($return_date);
	}
Any help gratefully accepted!

Rob

:)

Posted: Mon Oct 10, 2005 6:15 am
by jayshields
your new function is exploding on "-", which will give you "00", "00", "00 00:00:00" as far as I'm aware.

explode on ":" and you will get "00-00-00 00", "00", "00".

so you could explode on ":" as said above and then trim the first 9 characters from the first entry in the array.

so you could do this:

Code: Select all

$parts = explode(":", $date);
$hour = substr(9, $parts[0]);
$minute = $parts[1];
$second = $parts[2];
$time = $hour . ":" . $minute . ":" . $second;
lol, just looking back on that, you could do it like this...

Code: Select all

$parts = explode(" ", $date);
$time = $parts[1];
so try:

Code: Select all

function convert_date_time($date) {
  $date = "$date";
  $parts = explode(" ", $date);
  $time = $parts[1];
  return ($time);
}
HTH.

Posted: Mon Oct 10, 2005 7:37 am
by robster
totally perfect!

A silly question as I'm new to this kind of explode array stuff, but how did you know time would be in '1' of the array?

Posted: Mon Oct 10, 2005 8:28 am
by jayshields
i knew because when you feed something into an array, the first entry will be in $var[0], the second entry will be in $var[1], and so on.

so for example, if you exploded "jay, rob, fred, bob" into an array with ", " as the string to explode on, jay would be indexed as 0, rob as 1, fred as 2 and bob as 3.

glad it worked btw :)

Posted: Mon Oct 10, 2005 8:57 am
by Jenk
for future reference, sscanf is a wonderful function for this sort of purpose:

Code: Select all

list($month, $day, $year) = sscanf("%d-%d-%d 00:00:00", $date);

Posted: Mon Oct 10, 2005 3:30 pm
by feyd
what's wrong with using DATE_FORMAT() ?