PHP - Calculating With Times
Hi everyone,
I'm trying to add up the current time with a specified amount of seconds and insert it in a database afterwards. When I add say: 500 seconds to the current time it adds a whole lot more and I get a number few thousands higher than I want. Can anyone help me???. Gr Ryflex Similar TutorialsHello, I am having a heck of a time trying to get time right on my website lol When a user logs in, they select what timezone they are in (UTC -1,-2,-3,-4,-5,-6....) Now this is great an all, but with daylight savings time my times are off by one hour in either direction. How do sites like this get times to work for users so easily? Thanks! weee Hello all, I'm collecting date/time information via a form and would like to convert the info into something that I can stick in my MySql database (a timestamp???). I'm collecting the current month (variable name: month-- of the form "mm"), day (variable name: day -- of the form "dd"), year (variable name: year -- of the form "yyyy"), time of day (variable name: time -- of the form "h:00"), and before or after noon (variable name: ampm -- of the form "am" or "pm"). Any suggestions as to how to change this into a quantity that I can store as a value and then use to compare to other date/times would be appreciated. Thanks! I have a form that I will post the code for. In my form I have a few things that need to be filled out.... Age, Gender, Coverage Amount, and Health Conditions. The Health Conditions are 5 check boxes the user can select. Now what I'm trying to do is make it so that when the user hits submit the Age and number of Health Conditions checked off will do this... if # of Health Conditions <=2 and Age is <= 30 then = $0.90 if # of Health Conditions =>2 but <=5 and Age is <= 30 then = $1.20 Then after those are calculated I need these to apply to the code... - Men are charged a 5% gender risk - Students receive an 8% discount Here is a example of what I'm trying to get this to do... If you are a 23 year old male student who smokes but has no other risk factors your premium amount per $10,000 would be $0.90 * 1.05 * 0.92 = $0.8694. If you wanted to take out a $150,000 life insurance, your monthly premium would be $13.04 (15 * $0.8694). I'm doing a life insurance form and these are some of the calculations that need to go into it. I'm not sure how I would code these. If someone could help me get started that would be great. Here is my form code and the display page. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Lab 4</title> </head> <body> <?php ?> <form method="POST" action="lab4form.php"> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" /><br /> <label for="last_name">Last Name:</label> <input type="text" id="last_name" name="last_name" /><br /> <label for="coverage_amount">Coverage Amount:</label> <input type="text" id="coverage_amount" name="coverage_amount" /><br /> <label for="gender">Gender:</label> <br> <input id="male" type="radio" value="Male" name="gender" /> <label for="male">Male</label> <input id="female" type="radio" value="Female" name="gender" /> <label for="female">Female</label> <br /> <br> <label for="Age">Age:</label> <input type="text" id="age" name="age" /><br /> <br> <label for="health">Health Conditions</label> <br /> <input type="checkbox" name="health" value="Heart Disease" /> <label for="health">Heart Disease</label><br /> <input type="checkbox" name="health" value="Diabetes" /> <label for="health">Diabetes</label><br /> <input type="checkbox" name="health" value="High Blood Pressure" /> <label for="health">High Blood Pressure</label><br /> <input type="checkbox" name="health" value="Smoker" /> <label for="health">Smoker</label><br /> <input type="checkbox" name="health" value="Lung Disease" /> <label for="health">Lung disease</label><br /> <FORM METHOD=POST ACTION="lab4form.php"> <P>Employment Status<BR> <SELECT NAME="employment"> <OPTION VALUE="Unemployed">Unemployed <OPTION VALUE="Full-Time">Full-Time <OPTION VALUE="Part-Time">Part-Time <OPTION VALUE="Student">Student </SELECT><br /> <br> <label for="comments">Comments</label> <input type="text" id="comments" name="comments"/><br /> <br> <input type="submit" value="Add User" name="btn_add" /> </form> </body> </html> Display Page Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Lab4</title> </head> <body> <div id="page"> <div id="main"> <div id="content"> <h2>Life Insurance</h2> <table> <tr> <th>Coverage Amount</th> <th>Name</th> <th>Gender</th> <th>Age</th> <th>Health Conditions</th> <th>Employment Status</th> <th>Comments</th> </tr> <?php $coverage_amount = $_POST['coverage_amount']; $age = $_POST['age']; $health = $_POST['health']; if $age = ?> <tr> <td><?php echo $_POST['coverage_amount'];?></td> <td><?php echo $_POST['first_name'];?></td> <td><?php echo $_POST['gender'];?></td> <td><?php echo $age?></td> <td class="right"><?php echo $_POST['health'];?></td> <td class="right"><?php echo $_POST['employment'];?></td> <td><?php echo $_POST['comments'];?></td> </tr> </table> </div> </div> <div id="footer"></div> </div> </body> </html> Not asking someone to do this for me. Just looking for someone to help me get going, and show me how to do this. Need helping calculating text boxes on a form. I want my form to display the premium of $10,000 health insurance. What I mean by this is that I have a form that involves filling out life insurance information. This is the table I'm basing this off of... Age <=30 #health conditions <=2 $0.90 2 <= #health conditions <=5 $1.20 The number of health conditions is equivalent to the number of check boxes that were checked. Additionally, the following conditions apply: - Men are charged a 5% gender risk - Students receive an 8% discount For example, if you are a 23 year old male student who smokes but has no other risk factors your premium amount per $10,000 would be $0.90 * 1.05 * 0.92 = $0.8694. If you wanted to take out a $150,000 life insurance, your monthly premium would be $13.04 (15 * $0.8694). I'm new to php and haven't really calculated forms before... here is my form codes.... Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Lab 4</title> </head> <body> <?php ?> <form method="POST" action="lab4form.php"> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" /><br /> <label for="last_name">Last Name:</label> <input type="text" id="last_name" name="last_name" /><br /> <label for="coverage_amount">Coverage Amount:</label> <input type="text" id="coverage_amount" name="coverage_amount" /><br /> <label for="gender">Gender:</label> <br> <input id="male" type="radio" value="Male" name="gender" /> <label for="male">Male</label> <input id="female" type="radio" value="Female" name="gender" /> <label for="female">Female</label> <br /> <br> <label for="Age">Age:</label> <input type="text" id="age" name="age" /><br /> <br> <label for="health">Health Conditions</label> <br /> <input type="checkbox" name="health" value="Heart Disease" /> <label for="health">Heart Disease</label><br /> <input type="checkbox" name="health" value="Diabetes" /> <label for="health">Diabetes</label><br /> <input type="checkbox" name="health" value="High Blood Pressure" /> <label for="health">High Blood Pressure</label><br /> <input type="checkbox" name="health" value="Smoker" /> <label for="health">Smoker</label><br /> <input type="checkbox" name="health" value="Lung Disease" /> <label for="health">Lung disease</label><br /> <FORM METHOD=POST ACTION="lab4form.php"> <P>Employment Status<BR> <SELECT NAME="employment"> <OPTION VALUE="Unemployed">Unemployed <OPTION VALUE="Full-Time">Full-Time <OPTION VALUE="Part-Time">Part-Time <OPTION VALUE="Student">Student </SELECT><br /> <br> <label for="comments">Comments</label> <input type="text" id="comments" name="comments"/><br /> <br> <input type="submit" value="Add User" name="btn_add" /> </form> </body> </html> I have a timestamp field in my mySQL table and need to check if it's 14 day or older. What's the best way to do this? Any help will be appreciated hi all, i'm trying to calculate the time difference between two dates in hours, for example: 2010-12-13 15:26:56 and 2011-12-13 15:26:56 i tried mktime but wasn't able to get a working function. Thanks for the help Hi, This query will show match stats of a user, the query is the output in the attatchment. I want to calculate the streak if score1 is greater than score2. So basically, in the attatchment I have selected 3 rows, these 3 rows should be a 3 streak because the user won 3 matches in a row (according to date) Code: [Select] SELECT * FROM webs_cup_matches WHERE ladID='17' AND (clan1 != '0' AND clan2 != '0') AND (clan1='2630' || clan2='2630') AND (clan1 != '2147483647' AND clan2 != '2147483647') ORDER BY date DESC any help appreciated. Hello Please can someone PLEASE PLEASE help me. I have a form that the user inputs dimension and weights of a parcel. They then request a price on request I do the following: $volume_mass = 50(dimm1) *50 (dimm2) * 50 (dimm3); so that means $volume_mass = 125000 I then take the total of the weight - $actual_mass = 20(weight) I am doing the following query to see what service are available $data = "SELECT * FROM rates WHERE hub_from = 'nxd' AND hub_to = 'auk'"; $result = mysql_query($data) or die ("Error in query: $data. " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_object($result)) } ?> So I get multiple results and I need to now work out the cost per result. Example of results from rates table $service $volume $base $min_kg $per_kg AIR 5000 70.00 5 4 ECO 4000 80.00 10 4 LOX 5000 45.00 1 35 LSE 5000 45.00 1 35 OVN 5000 70.00 10 4 Know I need to do the following per result (per service) need to the volume factor from the service - &totalv = $volume_mass / $volume (from the rates table) Check if which is now greater between $actual_mass and $totalv - $charge_mass = $actual_mass <> $totalv then need to calculate the costs - if $charge_mass <= $min_kg then $total_cost = $base echo "$total_cost" else if $charge_mass > $min_kg then $total_cost = ($charge_mass - $min_kg) *$per_kg + $base echo "$total_cost" Any help would be greatly appreciated Hey everyone, Im writing some code that has to work out a route based on linking airports and output all the flights it takes to get there, tried searching just dont really know what to search for The data table looks like this ID, Origin, Destination, DatetimeDeparting, DatetimeArriving, Price 1, BKK, CNX, 2010-10-14 12:00:00, 2010-10-14 14:00:00, 125 2, STN, BKK, 2010-10-13 18:00:00, 2010-10-13 22:00:00, 300 etc. What is the easiest way of working out the path from STN to CNX via BKK? UPDATE: Just to make it more interesting there will be instances where there is more than 1 path eg. STN -> KUL -> BKK -> CNX hey guys just a quick onei having a blank moment i have an array at themoment pulling from a database. i basically want to split this array based on a min and max value. divide it equally and then give it a value on each smaller array and where each array starts... to make it clearer - say i have an array with 600 values in i want it split up into 8 smaller arrays link so Array ( => Array ( [start] => 0 [split] => 75 ) [1] => Array ( [start] => 75 [split] => 75 ) [2] => Array ( [start] => 150 [split] => 75 ) carrying on till the end ) how would i do this. Hello Please take a look at attatchment: Lets say for example I wanted to check the streak of clan1 (column) = 9 (rows) The streak would be 5 because each row has score1 greater than score2. So I want to calculate the streak of the value in clan1 column that has score1 greater than score2 in rows, if score2 is greater than score1 in a row then the streak breaks if that makes sense? let me know if I need to re-phrase. Secondly, if there are two streaks, I want it to calculate the highest one. Thanks for any help !! Hi, im trying to calculate and display a time elapsed from known date in db. however im having trouble displaying it. other values display no problem, just cant calculate and display date on the fly. does anyone see a problem with my query? thank you. Code: [Select] <?php include('config.php'); $uname=$_SESSION['username']; if($_SESSION['username']){ $sql="SELECT country, nationality, passportDate FROM country WHERE uname='$uname'"; $result = mysql_query($sql) or die(mysql_error()); $passportDate _ts = strtotime($row['passportDate ']); $passportDate _str = date("M-d-Y", $passportDate _ts); $TotalTime = floor((time() - $passportDate _ts)/(60*60*24)) . ' days'; while($row=mysql_fetch_array($result)) { echo "<table border='0'> <tr> <th>Nationality</font></th> <th>Country</font></th> <th>Passport Seent Date</font></th> <th>Time Elapsed</font></th> </tr>"; echo "<tr>"; echo "<td>" . $row['nationality']."</td>"; echo "<td>" . $row['country'] . "</td>"; echo "<td>" . $row['passportDate '] . "</td>"; echo "<td>" . ('$TotalTime') . "</td>"; echo "</tr>"; } echo "</table>"; } ?> I have a table with Territory Representative Sales. It has columns that go back 26 months. The columns are SALES_OLDEST_PD_1, SALES_PD_2, SALES_PD_3, ..... SALES_PD_25, SALES_LAST_PD_26, & SALES_CURR_PD_27. SALES_CURR_PD_27 is the current month. I want to build a table with "Last Year To Date Sales" (LYTD), "Current Year To Date Sales" (CYTD), (May 2011), and (May 2010). I know that (May 2011) will be SALES_CURR_PD_27 and (May 2010) will be SALES_PD_15. The trick is that the sales year starts in November. So, I need to figure out a way to match the table columns with "Nov. 09 - May. 10 TOTAL" for (LYTD) and "Nov. 10 - May. 2011 TOTAL" for (CYTD). I am familiar with using mktime() to subtract months. But, I am not sure where to start yet on this project. Jake Code: [Select] while (odbc_fetch_row($rs)) { $M1 += odbc_result($rs,"SALES_OLDEST_PD1"); $M2 += odbc_result($rs,"SALES_PD2"); $M3 += odbc_result($rs,"SALES_PD3"); $M4 += odbc_result($rs,"SALES_PD4"); $M5 += odbc_result($rs,"SALES_PD5"); $M6 += odbc_result($rs,"SALES_PD6"); $M7 += odbc_result($rs,"SALES_PD7"); $mate += odbc_result($rs,"SALES_PD8"); $M9 += odbc_result($rs,"SALES_PD9"); $M10 += odbc_result($rs,"SALES_PD10"); $M11 += odbc_result($rs,"SALES_PD11"); $M12 += odbc_result($rs,"SALES_PD12"); $M13 += odbc_result($rs,"SALES_PD13"); $M14 += odbc_result($rs,"SALES_PD14"); $M15 += odbc_result($rs,"SALES_PD15"); $M16 += odbc_result($rs,"SALES_PD16"); $M17 += odbc_result($rs,"SALES_PD17"); $M18 += odbc_result($rs,"SALES_PD18"); $M19 += odbc_result($rs,"SALES_PD19"); $M20 += odbc_result($rs,"SALES_PD20"); $M21 += odbc_result($rs,"SALES_PD21"); $M22 += odbc_result($rs,"SALES_PD22"); $M23 += odbc_result($rs,"SALES_PD23"); $M24 += odbc_result($rs,"SALES_PD24"); $M25 += odbc_result($rs,"SALES_PD25"); $M26 += odbc_result($rs,"SALES_LAST_PD26"); $M27 += odbc_result($rs,"SALES_CURR_PD27"); } Note: By the way SMF is changing $M"8" to $M"ate". lol I tried using a for loop but I'm trying to think of a way to calculate interest for a number of years but after I have the amount of interest for one year I'm unsure of how to add the interest to the principle then calculate it again for the next year, to hold that number like $Principle + $Interest = $NewPrinciple then $NewPrinciple + $Interest for multiple years. <?php if (isset($_POST['submit'])) { $InvestmentFrequency = $_POST['InvestmentFrequency']; $CompoundFrequency = $_POST['CompoundFrequency']; $InitialInvestment = preg_replace("/[^0-9]/", '', $_POST['InitialInvestment']); $Contributions = preg_replace("/[^0-9]/", '', $_POST['Contributions']); $InvestmentLength = preg_replace("/[^0-9]/", '', $_POST['InvestmentLength']); $InterestRate = $_POST['InterestRate']; if ($InvestmentFrequency == "Weekly") { $InvestmentFrequency = "52"; } elseif ($InvestmentFrequency == "Monthly") { $InvestmentFrequency = "12"; } else { $InvestmentFrequency = "1"; } if ($CompoundFrequency == "Annually") { $CompoundFrequency = "1"; } elseif ($CompoundFrequency == "Semiannually") { $CompoundFrequency = "2"; } elseif ($CompoundFrequency == "Monthly") { $CompoundFrequency = "12"; } elseif ($CompoundFrequency == "Weekly") { $CompoundFrequency = "52"; } else { $CompoundFrequency = "365"; } if ($CompoundFrequency == "1") { $AdditionalInvestments = $Contributions * $InvestmentFrequency; $Principle = $InitialInvestment + $AdditionalInvestments; $Interest = $Principle * $InterestRate; $NewPrinciple = $Principle + $Interest; for ($x = 0; $x <= $InvestmentLength; $x++){ echo "$x - $NewPrinciple</br>"; } } } This is the output I get the principle and interest added together for the number of years I entered. Edited July 26, 2020 by dataxspy I have this block of code that was written by someone years ago :-
<?php class BoDelivery { public function EstimatedDays($off, $standard_days, $saturday, $delay) { $today = date("N"); // Weekday - number 1-7 $now = strtotime("now"); // Unix $off_array = explode(":", str_replace(".", ":", $off)); $off_unix = mktime($off_array[0], $off_array[1], "00", date("n"), date("j"), date("Y")); $sending_days_from_now = 0; if ($now > $off_unix) { $sending_days_from_now++; } $sending_day = $today + $sending_days_from_now; switch ($sending_day) { case 6: $sending_days_from_now++; $sending_days_from_now++; break; case 7: $sending_days_from_now++; break; } $sending_day = $today + $sending_days_from_now; // Estimated delivery time $delivery_days = $standard_days; $over_weekends = 0; // Add Delay if ($delay) { $delivery_days = $delivery_days + $delay; } if ($sending_day == 5 && !$saturday) { $delivery_days++; $delivery_days++; $over_weekends++; } $delivery_day = $sending_day + $delivery_days; switch ($delivery_day) { case 6: if (!$saturday) { $delivery_days++; $delivery_days++; $over_weekends++; } break; case 7: $delivery_days++; $over_weekends++; break; } if ($over_weekends == 0 && $delivery_days > 5) { $delivery_days++; $delivery_days++; } $delivery_day = $sending_day + $delivery_days; switch ($delivery_day) { case 13: $delivery_days++; $delivery_days++; $over_weekends++; break; case 14: $delivery_days++; $over_weekends++; break; } $delivery_day = $sending_day + $delivery_days; $delivery_days = $delivery_day - $today; return $delivery_days; } } ?>
Which is supposed to calculate the number of days for delivery, taking into account weekends & with a delay variable that we can set. It isn't working as expected, may never have worked(??) or maybe down to PHP upgrades. For example, if today (18th)I set the delay to 2 days the delivery estimate is the 21st (which is correct), if I change the delay to 3 OR 4 it becomes the 24th, 5 then becomes the 26th! I can't get my head around the code at all, I wonder if someone could assist in what may be going on or add comments to the code snippets so I can maybe work it out?
Thanks for any help. Okay guys, I figured out how to calculate monthly subscriptions into days, but I am stuck on calculating multiple monthly subscriptions.. for example Heres my mysql table: How would I calculate this: Subscription Start: February 21, 2011, 12:00 am Subscription End: April 22, 2011, 12:00 am Subscription Left: 60 days My trouble is that when the user buys another month, it calculates the end time based on the new "Subscription Start Date". Or vice versa. Any ideas guys? Thanks. I am in the process of trying to create a pedigree website (php/mysql)...
I want to be able to calculate a dog's inbreeding coefficient on 10 generations.
I am so not sure where to even begin.
I have a database table:
dogs:
Fields: id name sireid damid
equation:
FX = å [ (½) n1+n2+1 (1 + FA)]
http://www.highflyer...coefficient.htm
Can someone give me a starting point?
Do I need to learn bianary trees? could I do this with an array?
Thanks
Edited by Triple_Deuce, 20 November 2014 - 01:27 PM. I'm trying to build a math game. But I'm having trouble trying to make a variable calculate that contains an operator. Example: $c1_op = "+"; $a1_num_user = $_POST['a1_num']; $e1_num_user = $_POST['e3_num']; $row_1 = $a1_num_user . $c1_op . $e1_num_user; echo "result: " . $row_1; If I now input a 10 and a 2 I will get echo'd out: result: 10+2 It's not calculating. When I don't use any quotation marks then I will get the error "unexpected ;". I need the operator inside a variable, it's the nature of the math game, any idea how I can make it work so it calculates? 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'); } } |