PHP - Two Timestamps, Detailed Breakdown Of Distance.
Getting the difference in seconds between two timestamps is easy. Taking the seconds and doing a breakdown of time frames is also easy.
Code: [Select] <?php echo '<p>There are a total of ' . round($seconds) . ' seconds between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round($seconds / 60) . ' minutes between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round(($seconds / 60) / 1440) . ' days between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((($seconds / 60) / 1440) / 7) . ' weeks between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((((($seconds / 60) / 1440) / 7) / 30)) . ' months between Timestamp 1 and Timestamp 2.</p>'; echo '<p>The total breakdown of time from Timestamp 1 to Timestamp 2 is .</p>'; ?> What I am trying to figure out, is get a collective amount as well.... X years X months X weeks X days X minutes and X seconds. Does anyone have any good algorithm for handling that, or have any feedback on where to start to handle this type of math. Similar TutorialsHi I have built a series of forms with PHP and have been using SESSIONS to carry values from one to another. In one, the value of a variable is determined by adding the values of several other variables together: Code: [Select] $totalFixed = $fixedCost1 + $fixedCost2 + $fixedCost3 + $fixedCost4 + $fixedCost5;This equation is working fine on that page. I then place the value of $totalFixed in a SESSION variable: Code: [Select] $_SESSION['totalFix']=$totalFixed;I then assign this SESSION variable's value to a new variable on another page in the series: Code: [Select] $dataValue[4] = $_SESSION['totalFix'];The number displays fine on this page as well. However, when the value is above 1,000 and I try to subtract another number from it, it ignores everything to the right of the comma. For example, if $dataValue[4] is 10,132 and $dataValue[5] is 25 and I subtract $dataValue[4] from $dataValue[5], the result is -15. Does anyone know the reason for this? Many thanks, Andy Im new to PHP and have had success with much help from the community and am greatly thankful for all input. I have a pretty good understanding of what needs to be done, but actually implementing and accomplishing is difficult for me. Im trying to break down hierarchy from an existing HTML list. First Id like to point out that I am working with an HTML file that I must use, and cannot change, as the source. I am rewriting onto another file, removing HTML, and so forth. I have already accomplished this. But what I would really like to keep the hierarchy structure by breaking it down first, so I can also use that later. Example HTML list Code: [Select] <ul><li>modem, UP</li> <ul><li>wifiRouter, UP</li> <ul><li>PC1, DOWN</li> <ul></ul> <!-- Open-close of UL identifies end --> </ul> <!-- Up one level --> <ul><li>wiredRouter, UP</li> <ul><li>server, UP</li> <ul><li>dnsServer, UP</li> <ul></ul> <!-- Open-close of UL identifies end --> <ul><li>webServer, UP</li> <ul></ul> <!-- Open-close of UL identifies end --> </ul> <!-- Up one level --> <ul><li>PC2, UP</li> <ul></ul> <!-- Open-close of UL identifies end --> </ul> <!-- Up one level --> </ul> <!-- Up one level --> <ul><li>modemBackup, DOWN</li> <ul></ul> <!-- Open-close of UL identifies end --> </ul> Desired Output: Code: [Select] 1, 0, 0, 0, modem, UP 1, 1, 0, 0, wifiRouter, UP 1, 1, 1, 0, PC1, DOWN 1, 2, 0, 0, wiredModem, UP 1, 2, 1, 0, server, UP 1, 2, 1, 1, dnsServer, UP 1, 2, 1, 2, webServer, UP 1, 2, 2, 0, PC2, UP 2, 0, 0, 0, modemBackup, DOWN If im logically looking at this right (1) Count <ul> entry and continue counting for each group (2) Stop group count at end argument <ul></ul> (3) The immediate next end argument </ul>, following (2), says to continue counting the previous group +1 (4) Repeat steps 1-3 until end Any advise? PLEASE NOTE: I did check the PHP manual, although it was a bit too confusing for beginners with timestamps. I'm creating a simple bank interest system for my PHP game. Say I have a 2% interest in my bank, and I want to run it every 20 minutes. How would I do this? Please provide an example as I'm a bit...too lost. :/ Hello, input: I have a timestamp 1309438800 at GMT 1pm (2011-06-30 13:00:00 PM) output: how to make this timestamp at 1pm PST? cheers! ok so i am using relative timestamps on my forum. if a post was created less than 1 hour ago then it will display something like 32 minutes ago. If it was posted more than 1 hour ago it will display "posted today at 10:00pm", or if it was older than 1 day then it will display the absolute time stamp. My question is how do i get them to update automatically like facebook does? i would like to use jquery for this but after searching i cant make heads or tales of any of it. so to sumarise i would like the timestamps to update without having to refresh the page. Thanks Hi, I have 2 db fields with timestamp datatype (ClockingInDate and ClockingOutDate) and i am trying to get the difference between them then update the new db called duration with float datatype field. PHP: if (isset($_POST["clockout"])){ $result3=mysqli_query($con, "select * from attendance_records where OracleID='$session_id'")or die('Error In Session'); $row3=mysqli_fetch_array($result3); $end_date = $row3['ClockingOutDate']; $startdate = $row3['ClockingInDate']; $diff = strtotime($end_date) - strtotime($startdate); $fullDays = floor($diff/(60*60*24)); $fullHours = floor(($diff-($fullDays*60*60*24))/(60*60)); $fullMinutes = floor(($diff-($fullDays*60*60*24)-($fullHours*60*60))/60); $duration = $fullMinutes; $query3=mysqli_query($con, "update attendance_records set Duration = '$duration' where OracleID='$session_id' and isdone='$isdone'")or die('Error In Session'); header('location:index.php'); }
* come to think of that again, i always get zero, is it because it never reaches days in my program! I am using this for attendance system so only hours and minutes are used. Please help. Edited March 13, 2020 by ramiwahdanthoughts How do I show how many miles away the nearest location is? This code works with showing stores within the radius of the zip code entered, but it does not show the miles. Can anybody see what I have to do to display the miles? Code: [Select] <?php // Create page variables $r = NULL; $z = NULL; $stores = NULL; $Errors = NULL; include('inc/connect.db.mrk.php'); // Declare page functions function Dist($lat1, $lon1, $lat2, $lon2) { $distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } ### Handle form if submitted if (isset ($_POST['submitted'])) { // Validate Postcode code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $z = (int)$_POST['zip']; // Verify Postcode code exists $query = "SELECT latitude, longitude FROM zipdata WHERE zip = '$z'"; //$result = mysql_query ($query); $result=mysql_query($query) or die ('Invalid query.'); if (mysql_num_rows ($result) == 1) { $zip = mysql_fetch_assoc ($result); } else { $Errors = '<p>The postcode code you entered was not found!</p>'; $z=NULL; } } // Validate radius field if (isset ($_POST['radius']) && is_numeric ($_POST['radius'])) { $r = (int)$_POST['radius']; } // Proceed if no errors were found if ($r && $z) { // Retrieve coordinates of the locations $result = mysql_query("SELECT LocAddState, MktName, LocAddSt, LocAddZip, LocAddCity, x1, y1 FROM store INNER JOIN zipdata ON store.LocAddZip=zipdata.zip") or die(mysql_error()); //$result = mysql_query ($query); // Go through and check all locations while ($row = mysql_fetch_assoc ($result)) { // Separate closest locations $distance = Dist($row['y1'], $row['x1'], $zip['latitude'], $zip['longitude']); // Check if store is in radius if ($distance <= $r) { $stores[] = array ( 'name' => $row['MktName'], 'address' => $row['LocAddSt'], 'state' => $row['LocAddState'], 'town' => $row['LocAddCity'], 'postal' => $row['LocAddZip'], ); } } } else { $Errors = ($Errors) ? $Errors : '<p>Errors were found please try again!</p>'; } } ?><html> <head> <title>Store Locator</title> </head> <body> <form action="" method="post"> <p>Enter your zip code below to find locations near you.</p> <?php echo ($Errors) ? $Errors : ''; ?> <div> <label>Zip:</label> <input name="zip" type="text" size="10" maxlength="5" /> </div> <div> <label>Search Area:</label> <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> </div> <div> <input type="hidden" name="submitted" value="submitted" /> <input type="submit" value="Submit" /> </div> </form> <?php if (isset ($stores)) { if (!empty ($stores)) { echo '<p><strong>' . count ($stores) . ' results were found.</strong></p>'; foreach ($stores as $value) { echo '<p><strong>' . $value['name'] . '</strong><br />'; echo $value['address'] . '<br />'; echo $value['town'] . ', ' . $value['state'] . ' ' . $value['postal'].'<br />'; echo $distance . ' miles away <br />'; /*echo ' <a target="_blank" href="http://maps.google.com/maps?q=', $value['address'], ' ', $value['town'], ', ', $value['state'], ' ', $value['postal'], '">Map this location</a><br />'; */ echo '</p>'; } } else { echo '<p><strong>No results found</strong></p>'; } } ?> </body> </html> Right now it shows like this Code: [Select] 1482.92070414 miles away Thanks in advance Why doesn't this code work... echo '<p>time() = ' . time() . ' seconds</p>'; echo '<p>$lastActivity = ' . $lastActivity . '</p>'; echo '<p>Seconds Active: ' . time() - $lastActivity . ' seconds</p>'; ...where $lastActivity comes from my database. When I run my script I see... Quote time() = 1331187131 seconds $lastActivity = 1331186745 -1331186745 seconds The last line is dropping the label and there is now Date Math?! Debbie Hi, Hope this is the right place for this... I have php routines that print itineraries. For some reason the timestamp (1351378800) returns the same date Sunday 28th October (2012) as the time stamp (1351465200). $count = 0; while ($count <= ($nights+1)) { echo date ('l', $startdate1)." (".$startdate1.")"; echo "<br>"; echo date ('jS F', $startdate1); $startdate1 += 86400; // more code } Any ideas? Many thanks, Peter hi, there. I have a timestamp in my mysql database called timestamp and it'll record the current timestamp. however it also records the time etc how do i use php to take apart these for example if i wanted to echo the date and time in a different order or if i only wanted to echo the date not the time. how is this possible? Thanks for reading. Ok sorry if this is a proper newbie question but say i have a timestamp saved in a database in a table called "news" and the field is called "date" how do i get the month and year only from example if the time stamp is 2011-03-29 13:57:05. And i want to list all news articles from the month 03 and the year 2011 how would i go about doing this? Thank you for reading As you may of guessed, it's a nightmare. If my birthday is on 10th June GMT, it would still be my birthday on the 11th June in Australian time. Though.. the 11th June, is not my birthday. It's not hard to understand this bit as Australia is like.. many hours ahead. Though when it comes to PHP... if I used some Timezone plug-in then this would bring up the same result as it does now. Though when that persons age is displayed... if my birthday is 10th June at 1AM, in America, it would be the 9th June. There for, they won't see my age change to 18 until it is 10th June their time. To prevent this, is when calculating the persons age, you would be adding their timezone offset onto their birthday timestamp. So regardless on what day it is around the world, if they are celebrating their birthday... then it's their birthday all around the world even though it's different times. To do this, i would need timezone offsets. I would have a field in the database I assume. I would convert their DOB to timestamp. I would add their offset onto that timestamp or take it away and display whatever result that gives to every user. This would display their age as whatever to every user. The next problem is... strtotime works in MM/DD/YYYY, so how do I make it work with DD/MM/YYYY ? I'm actually not making much sense, how would you work with Timestamps and Ages? Also for my next question question, if I had someones DOB, how do I bring up their next birthday out of it for when I am displaying "Bobs birthday is on the..." Now for final, apparently on 19th Jan 2038 the UNIX Timestamp will cease to work due to a 32-bit overflow. How can this be true when converting a date in the year 2500 still brings a timestamp?
Hi,
Write a function that calculates the Euclidean distance for points: eucl(q1,z1,r2,z2). Date:
$r1=1; $z1=12; $r1=43; $z1=123;
formula to the Euclidean distance: (r1,z1,r2,z2)=sqrt[(r1-z1)*(r1-z1) + (r2-z2)*(r2-z2)],
Can anyone help? Hi, I just want to see what way you guys think is best. On this little community I'm building I have decided to implement a function to see who were active within the last 15 minutes. I made a table (just user and timestamp) to register the last activity of any logged on user. Then I have a variable to take off 15 minutes from that but I can't get them to compare. Googling the issue I found people are solving this in very different ways. I wanted to see what phpfreaks recommend as the next step. Here is some code (that doesn't work properly - no results found as I compare to different timestamps): Code: [Select] include_once'header.php'; $now=time(); $now=(date("Y-m-d H:i:s")); //$mins = mktime(0,$now-15,0, date("Y"), date("m"),date("d")); $mins = time(); $mins15 = $mins-(60*15); $mins15 = (date("Y-m-d H:i:s", $mins15)); $online="SELECT * FROM user_online" WHERE last_activity > mins15; $result = mysql_query($online); if (!$result) die ("Database access failed: " . mysql_error()); $rows = mysql_num_rows($result); echo <<< _END <div id='statusbar'> <h4>Online now: $rows</h4>
I made a post a while back about this topic he 1. The input from the project will be coming from a mobile app which will be using a qr code. The qr code contains the Room Number and the 2 Access Points for each room. When a user scans the qr code it will pass that info to the web app that has the algorithm and verify what room he/she is in the access point that was 'scanned'. 2. For the testing of the project we decided to use two rooms of the building of our alma mater and the access points were already defined based on tests:
Room 413 has Access Point 1 that have the values of -67 dBm to -89 dBm and Access Point 2 that have the values of -40 dbm to -57 dBm while
3. I already inputted the values and the rooms I've mentioned above in mysql to verify if the input from the qr code that was scanned it correct. but sadly we are stuck with the algorithm itself.
Okay guys. My brain has completely froze and I can't figure out how to do this. I have one date, that is somewhat static it doesn't change regularly but it changes. Anyway let's say this timestamp is: 2011-07-12 10:30:00 and the current timestamp is 2011-07-13 10:30:00 That's exactly a day difference, which will produce 86400 seconds. How would I write this in PHP? Hi, I have been using the following function on my server and it works fine but when I try and use it on a different server it wont seem to work. Any ideas on why it wont work on the new server and any ideas on how I can do some error checking to figure out why ? Thanks in advance, Scott Code: [Select] <?php function get_driving_information($start, $finish, $raw = false) { # Convert any lon / lat coordingates if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $start)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($start); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $start = trim(urldecode($found[1])); } else { throw new Exception('Start lon / lat coord conversion failed'); } } else { throw new Exception('Start lon / lat coord conversion failed'); } } if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $finish)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($finish); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $finish = trim(urldecode($found[1])); } else { throw new Exception('Finish lon / lat coord conversion failed'); } } else { throw new Exception('Finish lon / lat coord conversion failed'); } } if(strcmp($start, $finish) == 0) { $time = 0; if($raw) { $time .= ' seconds'; } return array('distance' => 0, 'time' => $time); } $start = urlencode($start); $finish = urlencode($finish); $distance = 'unknown'; $time = 'unknown'; $url = 'http://maps.google.co.uk/m/directions?saddr='.$start.'&daddr='.$finish.'&hl=en&oi=nojs&dirflg=d'; if($data = file_get_contents($url)) { if(preg_match('@<span[^>]+>([^<]+) (mi|km)</span>@smi', $data, $found)) { $distanceNum = trim($found[1]); $distanceUnit = trim($found[2]); if($raw) { $distance = $distanceNum.' '.$distanceUnit; } else { $distance = number_format($distanceNum, 2); if(strcmp($distanceUnit, 'km') == 0) { $distance = $distanceNum / 1.609344; } } } else { throw new Exception('Could not find that route'); } if(preg_match('@<b>([^<]*)</b>@smi', $data, $found)) { $timeRaw = trim($found[1]); if($raw) { $time = $timeRaw; } else { $time = 0; $parts = preg_split('@days?@i', $timeRaw); if(count($parts) > 1) { $time += (86400 * $parts[0]); $timeRaw = $parts[1]; } $parts = preg_split('@hours?@i', $timeRaw); if(count($parts) > 1) { $time += (3600 * $parts[0]); $timeRaw = $parts[1]; } $time += (60 * (int)$timeRaw); } } return array('distance' => $distance, 'time' => $time); } else { throw new Exception('Could not resolve URL'); } } I have this script that works 9/10 of how it's suppose too. This does not calculate the correct distance for the results. Can anybody see where the problem lies? Here is the code Code: [Select] // see if our zip code has been posted, and if it is a 5 digit # if (isset($_POST['zip'])) { // remember to sanitize your inputs // this removes whitespace around the data and the next line makes sure its a 5 digit number $findzip = trim($_POST['zip']); if (preg_match("#^\d{5}$#",$findzip)) { include('inc/connect.php'); include('inc/functions.php'); // create a query that will select the zip code (if we can't find the user entered zip, we return an error) $query = "SELECT latitude,longitude,state,city FROM zipdata WHERE zip=".$findzip." LIMIT 1"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { // grab the latitude, longitude,state and city from our result list($flat,$flon,$fstate,$fcity) = mysql_fetch_row($result); // now get all markets in the same state, or all markets if no states match // we want to reduce the amount of work the database has to do so we see if a state matches $query = "SELECT * FROM mrk WHERE state='".$fstate."'"; $result = mysql_query($query); if (mysql_num_rows($result) < 1) { $query = "SELECT * FROM mrk"; $result = mysql_query($query); } // now we process the markets to gather their data, //this result should not be empty, so I was lazy and didn't write an else case if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_assoc($result)) { // first put all of the data for this market into an array, with the market id as the key $storeinfo[$row['id']] = $row; // get the store zip $dzip = $row['zip']; // query for the store's latitude and longitude $query = "SELECT latitude,longitude FROM zipdata WHERE zip=".$dzip." LIMIT 1"; $result2 = mysql_query($query); if (mysql_num_rows($result2) > 0) { list($dlat,$dlon) = mysql_fetch_row($result2); // now get the distance from the user entered zip $stores[$row['id']] = calcDist($flat,$flon,$dlat,$dlon); } } } asort($stores); print "<p>The Markets closest to you: $findzip</p><br>\n"; $maploc = "'You are here','$findzip',"; foreach($stores as $k=>$v) { $output .= "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['company']."</b><br>(approx ".round($v)." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'><a href='".$storeinfo[$k]['url']."'>".$storeinfo[$k]['url']."</a><br>"; $output .= $storeinfo[$k]['city']." ".$storeinfo[$k]['state'].", ".$storeinfo[$k]['zip']."</p>"; } echo $output; } } } Here is the function.php Code: [Select] function calcDist($flat, $flon, $dlat, $dlon) { $distance = sin(deg2rad($flat)) * sin(deg2rad($dlat)) + cos(deg2rad($flat)) * cos(deg2rad($dlat)) * cos(deg2rad($flon - $dlon)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } Thank you in advance Hi Guys I need a PHP function to which I pass two postcodes and it works out the road distance, I dont mind using google or any other API I have managed to fing JS ways and php functions using crow route but I really really need a traffic distance in PHP Please advice, Help Thank you I have a page that gets the closest stores to a latitude and longitude. I want to have a MySQL table like this: location_id:::::items showing how many items are at each store and then show 'spit' them in the following format with the lowest number of items first: location_id, distance to location_id, items. here is the code I am using to show location_id by distance Code: [Select] <?php include "connectionfile.php"; $lat = $_GET["lat"]; $lng = $_GET["lng"]; $sql = mysql_query("SELECT id, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < 250 ORDER BY distance LIMIT 0 , 60; "); WHILE($lstlocations = mysql_fetch_array($sql)) { $location_id[$count]=$lstlocations['id']; $distance=$lstlocations['distance']; echo "id = " . $location_id[$count] . " Distance = " . $distance. "<br>"; $count = $count + 1; } ?> What would be the best way to achieve this? |