Forum Moderators: coopster

Message Too Old, No Replies

Extract Time from datetime string

         

capulet_x

4:42 am on Apr 19, 2007 (gmt 0)

10+ Year Member



I reading about the PHP time functions for a few hours now and I can't find a function to take something like this:

2007-04-16 13:49:01

to convert to this:

13:49:01

I still need the date for record purposes but I also need to calculate the time elapsed between two datetime entries. If I can extract the time I figured I can use basic subtraction to get the time used.

I thought I could use date_parse but I get this error:

Fatal error: Call to undefined function: date_parse()

This is the example I used right out of the PHP Manual

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

Can somone point me towards the correct function to use?

capulet_x

4:59 am on Apr 19, 2007 (gmt 0)

10+ Year Member



Okay, I see I get the error because date_parse is valid in (PHP 5 >= 5.1.3). I know that this particular DB that I'm accessing is PHP 4.1

capulet_x

7:01 am on Apr 19, 2007 (gmt 0)

10+ Year Member



Still need help extracting the time by itself though...

adb64

8:05 am on Apr 19, 2007 (gmt 0)

10+ Year Member



Take a look at the strtotime [php.net] function.

adb64

9:32 am on Apr 19, 2007 (gmt 0)

10+ Year Member



Was in a hurry when replying. The result of strtotime can be used as input for e.g. localtime [php.net] which will return an array with the same kind of information as date_parse.

capulet_x

7:29 pm on Apr 19, 2007 (gmt 0)

10+ Year Member



I always appreciate the responses I get here. I am very new to PHP but am realling finding it facinating.

This was my total solution. I would still love to know about more concise methods but this worked and I hope that this info is able to help someone so they don't spend the better part of a day trying to figure it out.

function get_mysql_to_epoch( $date )
{
list( $year, $month, $day, $hour, $minute, $second )
= split( '([^0-9])', $date );
return date( 'U', mktime( $hour, $minute, $second, $month, $day,
$year ) );
}

function get_elapsed_time(
$time_start,
$time_end,
$units = 'seconds',
$decimals = 2
)
{
$divider['years'] = ( 60 * 60 * 24 * 365 );
$divider['months'] = ( 60 * 60 * 24 * 365 / 12 );
$divider['weeks'] = ( 60 * 60 * 24 * 7 );
$divider['days'] = ( 60 * 60 * 24 );
$divider['hours'] = ( 60 * 60 );
$divider['minutes'] = ( 60 );
$divider['seconds'] = 1;

$elapsed_time = ( ( get_mysql_to_epoch( $time_end )
- get_mysql_to_epoch( $time_start ) )
/ $divider[$units] );
$elapsed_time = sprintf( "%0.{$decimals}f", $elapsed_time );

return $elapsed_time;
}

////Varibles Below.

///These shoud be in the datetime format.
$time_in = start;
$time_out = finish;

// The default is into seconds but you can use it for year,month,weeks,days,etc.
//echo '<br>Days: ';
//echo get_elapsed_time( $time_in, $time_out, 'days', 3 );

// Use defaults for units and decimal places.
//echo '<br>Seconds: ';
//echo get_elapsed_time( $time_in, $time_out );

//echo '<br>Hours: ';
//echo get_elapsed_time( $time_in, $time_out, 'hours');

//echo '<br>Minutes: ';
//echo get_elapsed_time( $time_in, $time_out, 'minutes');
$totaltime = get_elapsed_time( $time_in, $time_out);

echo $totaltime;

//Above was written by Steve Werby

//Below was written by J. Cornelius

//CONVERT SECONDS TO HH:MM:SS
$seconds = $totaltime;
$time = str_pad(intval(intval($seconds/3600)),2,"0",STR_PAD_LEFT)." "."hours"." "
. str_pad(intval(($seconds / 60) % 60),2,"0",STR_PAD_LEFT)." "."minutes"." "
. str_pad(intval($seconds % 60),2,"0",STR_PAD_LEFT) ." ". "secs" ;

echo $time;
?>

adb64

9:44 pm on Apr 19, 2007 (gmt 0)

10+ Year Member



Code looks fine, only the function get_mysql_to_epoch() does in your situation the same as the PHP function strtotime().
At the end, when calculating number of hours, calling intval() once is enough.

jatar_k

12:22 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I kept meaning to reply to this but for some reason also kept forgetting

>> more concise methods

a better method would be to also store the unix timestamp in a varchar field and then the math becomes easier

I looked around a bit and this wasn't what I was looking for but it looks interesting

[dev.mysql.com...]

a good page for reference for mysql functions is this
[dev.mysql.com...]

since mysql.com has the worst search I have ever seen

cameraman

7:19 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



store the unix timestamp in a varchar field

I always use bigint - varchar is preferred? Am I leading myself to a Y2216 bug (not that it would worry me!<grin>)?

capulet_x, you could use strtotime() to convert it to a timestamp, then take that value and use date() [php.net] to select out just the time parts (or getdate() [php.net] might be better for your purposes).
As jatar_k stated, timestamps make the math easier - convert your two dates to timestamps, do the subtraction, and the resulting value is the number of seconds between them.

jatar_k

10:11 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I just mean storing it as a string as opposed to a number/int/whatever

I just thought the small extra step of storing it at the time may save cycles later

cameraman

10:18 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, just making sure I wasn't missing something - I learn stuff from you guys on an almost daily basis. I learned something from you not 10 minutes ago (roundabout, but something I would not have learned had you not posted a link).

mayurapilly

11:04 pm on Apr 21, 2007 (gmt 0)

10+ Year Member



Maybe I am missing something, but why wouldn't you just do something like this:

assuming $theTime = "2007-04-16 13:49:01"

$arrTime=explode(" ", $theTime);
echo("Time is " . $arrTime[1]);

BananaFish

4:39 pm on Apr 22, 2007 (gmt 0)

10+ Year Member



If you want to accurately calculate the time between two dates, it's best to convert them to a Unix time stamp and calculate the number of seconds:

//initial time
$time1 = "2007-04-16 23:49:01";
//ending time
$time2 = "2007-04-17 00:09:13";
//get the time and date portions of the strings
list($date,$time)=explode(" ",$time1);
list($year,$month,$day)=explode("-",$date);
list($hour,$min,$sec)=explode(":",$time);
//get the unix timestamp
$utime1=mktime($hour,$min,$sec,$month,$day,$year);
//do the same for the ending time - fine candidate for a function
list($date,$time)=explode(" ",$time2);
list($year,$month,$day)=explode("-",$date);
list($hour,$min,$sec)=explode(":",$time);
$utime2=mktime($hour,$min,$sec,$month,$day,$year);
//subtract
$diff=$utime2-$utime1;
$minutes=$diff/60;
echo "minutes elapsed: $minutes \n";

This is why it's sometimes handy to store dates as unix timestamps (integers) rather that dates. Getting a date from a timestamp can be done in one line with the date() function.

You can also pull the dates from the db as timestamps with the mysql UNIX_TIMESTAMP() function to alieveate a lot of the code above.