PHP - How To Compare Dates?
I have this code that compares date times but im not sure if its correct.
if("2008-08-10 00:00:00.0" > strtotime("now")) { echo "here"; } The code echo's here, but it shouldn't because the time is less than the current time. Any ideas? Similar Tutorialshi i am am making a leave calendar ...i want to compare dates and if the matches the background will be changed . i am try to do is i got two loops first for 12 months and seconds for numbers of days in that month and i am using $num = cal_days_in_month(CAL_GREGORIAN, $Month, $cYear) this will give be numbers of days in that month... then there is a my sql query which will select that dates and other data from database .. now problem i am have is that numbers of days are not increment it show date like 2011-1-1 ,2011-1-1 and so on instead of 2011-1-1, 2011-1-2.... please help me ..here <<pre lang="xml">table > <?php for($Month=01;$Month <= 12;) { ?> <tr> <td width="18%" colspan="2"><strong><?php echo $monthNames[$Month-1]; ?></strong></td> <td width="12%" colspan="2"><strong>Division</strong></td> <?php $num = cal_days_in_month(CAL_GREGORIAN, $Month, $cYear); // 31 //$dates = date("$cYear-$Month-1"); $sql ="SELECT leave_date,leave_status,leave_comments,leave_type_id FROM `hs_hr_leave` WHERE employee_id = $emplid "; $res = mysql_query($sql); for($i=1;$i<=$num;$i++) { $dates = date("$cYear-$Month-$i"); //echo $dates."<br/>"; while ($row = mysql_fetch_row($res, MYSQL_NUM)) { $time2=date("Y-n-j",strtotime ($row[0])).'<br/>'; echo "<td bgcolor='red'>".$dates."--".$time2."</td>"; //echo "<td>".$row[1]."</td><br/>"; //echo "<td>".$row[1]."</td><br/>"; //echo "<td>".$row[2]."</td><br/>"; } echo "<td width='26' height='20px' align='center' valign='middle' >".$i."</td>"; } //echo "<br/>"; $Month++; } ?> </tr> </tabl I want to do something like this- $days_passed = daysPassed ($last_datetime); //returns (float)number of days (6 hours returns .25 days, 12 hours returns 0.5) $last_datetime = $getCurrentTime(); I will then store $last_datetime in the database for next time. I'm a bit overwhelmed by all the different time and date functions. Does someone have ready made functions that will work here? Hi All, I'm hoping someone can help as I've got myself in a muddle on some code. Basically, the form has a date field (date moved in). If the date entered is over 3 years old, all's ok However, if the date entered is less than 3 years old, the user needs to complete a list field. The list field is essentially a repeater field with a date and address field. If the user adds a date and address and this (plus the original date) is more than 3 years combined history - happy days! If the user adds a date and address and they've still not hit 3 years history, then I need to increase the number of rows (this is handled by another function which works by incrementing a field on the form. As it stands, it works until I need another field to appear i.e. they've entered the first date, then entered a date within the list/repeater field but still not got 3 years worth. I think it's more or less there but seem to have muddled some of the logic (I think/hope!). A fresh pair of eyes would be great: Here's my code: function dateDiffInDays($date1, $date2) { # Calulating the difference in timestamps $diff = strtotime($date2) - strtotime($date1); # 1 day = 24 hours # 24 * 60 * 60 = 86400 seconds return abs(round($diff / 86400)); } add_filter( 'gform_pre_render_2', 'applicant_2_previous_address_history' ); add_filter( 'gform_pre_validation_2', 'applicant_2_previous_address_history' ); function applicant_2_previous_address_history( $form ) { #get the value from the form date input d/m/Y so need to change $get_moved_in_date = rgpost( 'input_1' ); if ( $get_moved_in_date ) { #convert the date format $moved_in_date = date_format(date_create_from_format('d/m/Y', $get_moved_in_date), 'd-m-Y'); #echo "New date format is: ".$moved_in_date. "<br/>"; } #get todays date $today = date("d-m-Y"); #echo "<h3>Today: ".$today."</h3>"; #calculate the difference in days $dateDiff = dateDiffInDays($today, $moved_in_date); #printf("<p>Difference between two dates: " . $dateDiff . " Days</p>"); #check if we moved in less than 3 years ago if ( $dateDiff < 1095 ) { #less than 3 years, so need to loop through the list fields, compare dates and tally totals days if ( $days_sum < 1095 ) { # get the input from the list $list_values = rgpost( 'input_2' ); $i = 0; #use this to get even rows only due to the way data is stored :( $sum = 0; #use this to increment the no. of rows in the list $previous = null; #use this to calc date difference between rows $days_sum = $dateDiff; #set the total number of days. Don't start at 0, start from current date - time at current residence if ( $list_values ) { foreach ( $list_values as $key => $value ){ #get even rows only if($i%2 == 0){ #$sum = $sum + 1; #increment our rows if ( $value ) { #convert the date format $additional_date = date_format(date_create_from_format('d/m/Y', $value), 'd-m-Y'); #echo "<h3>Date: ".$additional_date."</h3>"; } if ( $previous !== null ){ # if it's null, we're in the first loop #convert the date format $previous_date = date_format(date_create_from_format('d/m/Y', $previous), 'd-m-Y'); $dateDiff2 = dateDiffInDays($additional_date, $previous_date); printf("<p>Next Iteration Difference between " . $additional_date . " and " . $previous_date . " is: " . $dateDiff2 . " Days</p>"); $days_sum = $days_sum + $dateDiff2; } else { #convert the date format $dateDiff1 = dateDiffInDays($additional_date, $moved_in_date); printf("<p>1st Iteration Difference between " . $additional_date . " and " . $moved_in_date . " is: " . $dateDiff1 . " Days</p>"); $days_sum = $days_sum + $dateDiff1; } $previous = $value; # set the current value, so it will be saved for the next iteration } $i++; } #end foreach $list_values } #endif $list_values $sum = $sum + 1; #increment our rows echo "<p>Total no of days = " .$days_sum.'</p>'; } #endif $days_sum < 1095 echo '<p>Not enough days so loop through list</p>'; $flag = 'true'; } else { echo '<p>Were ok!</p>'; $flag = 'false'; } #endif $dateDiff < 1095 /* if ( $dateDiff < 1095 ) { $value = 'yes'; } else { $value = 'no'; } */ #we moved in less than 3 years ago, so get history if ( $flag == 'false' ) { return $form; } foreach ( $form['fields'] as &$field ) { if ( $field->id == 2 ) { $field->isRequired = true; } echo "<p>The sum of array element is = " .$sum.'</p>'; if ( $field->id == 3 ) { $_POST['input_3'] = $sum; } } return $form; } Thanks I'm trying to do the following PHP. I have written it in English if (today's date) => date1 AND <= date2 then {display image1} elseif (today's date) => date3 AND <= date4 then {display image2} else {display image 13} There are 24 fixed dates and 13 fixed images. I have tried using combinations of strtotime(), replacing the date value with variables, hard coding the dates within the program. I don't seem to be able to get any combination to work properly. I'm sure it's just a syntax error but I can't see it. When I've searched the web all the answers I've found relate to dates within databases but as I only have 24 dates it seems a bit of overkill. I would appreciate any pointers to the correct method I might be able to use. The dates need only a day and month as I would like this to repeat year after year. <?php $today = strtotime(date('d-m')); if (strtotime($today) >= strtotime('28-10') && strtotime($today) <= strtotime('24-11')) {echo "<div>image1</div>";} elseif (strtotime($today) >= strtotime('25-11') && strtotime($today) <= strtotime('22-12')) {echo "<div>image2</div>" ;} elseif (strtotime($today) >= strtotime('23-12') && strtotime($today) <= strtotime('24-02')) {echo "<div>image3</div>" ;} else {echo "<div>image13</div>";} ?> The result I get from this is image1 appears on the web page but I would expect image3 as today is 22-01 Thank you in advance. Andrew Hi, I want to check entered dates and times that a user selects against my "book-off" calendar which is a Google Calendar. The dates× from Google is in the form: 2011-04-29T23:00:00.000+02:00 The dates in my booking software (ABPro) is in the form: 2011-04-29 Times in form: 23:00:00 All I want the function to return is a number other than 0 if any of the dates/times in Google feed overlap the requested date/time entered in the booking. So I add a function and get the feed from Google: Code: [Select] function checkOverlapG($calendarID, $startdate, $starttime, $enddate, $endtime){ // Create an instance of the Calendar service using an unauthenticated //HTTP client $service = new Zend_Gdata_Calendar(); //Retrieving events in order of start time $query = $service->newEventQuery(); $query->setUser('calendarID'); // Set to $query->setVisibility('private-magicCookieValue') if using MagicCookie auth $query->setVisibility('public'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setSortOrder('ascending'); //start with first event in future //seFutureevents must be commented out when using start and end times. $query->setFutureevents('true'); $query->setSingleEvents('true'); $query->setMaxResults('200'); //Guess this could be anything, but can possibly make things slower. Default 25 events //$query->setStartMin('2006-12-01'); //$query->setStartMax('2006-12-16); // setStartMax is exclusive, will not include last date. Must add +1 day. // Retrieve the event list from the calendar server try { $eventFeed = $service->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); return null; } Now I want to compare the dates and times and see if any of them collide or overlap. I want to add a counter, and if any of the events overlap, I want the counter to add one number. 1. the first thing I do is check if the event feed include. any events. 2. then I add a counter 3. then I run a foreach to retrieve events one at a time 4. then I change the date and time format from Google Event to match the date and time format form the booking. 5. If fullday event from google, no time information is added, so I add this 6. COMPARE DATES AND TIMES and if overlapping events --> n++; I've not gotten this code to work. Probably I'm doing something wrong, and I'm sorry but I'm completely new to this. Getting the Google Calendar data is working fine, and so is changing the format of the dates/times to be same format as request data. After that (and before, I don't know). Code: [Select] $gCount = count($eventFeed); $n = 0; if (gCount>0){ foreach($eventFeed as $event){ foreach ($event->when as $when) { //Getting rid of extra 00's and time zone info for now $startGevent = $when->startTime; $startGevent = str_replace('.000+02:00',"",$startGevent); $endGevent = $when->endTime; $endGevent = str_replace('.000+02:00',"",$endGevent); //Splitting date and time into two variables list($startDateEvent, $startTimeEvent) = split('T',$startGevent); list($endDateEvent, $endTimeEvent) = split('T',$endGevent); //Fill in the blanks if($startTimeEvent!=0) {} else{$startTimeEvent = "00:00:00";} if($endTimeEvent!=0) {} else{$endTimeEvent = "00:00:00";} //Compare dates if($startdate == $endDateEvent){ if($starttime > $endTimeEvent OR $endtime < $startTimeEvent){} else { n++; } } if($enddate == $startDateEvent){ if($endtime < $startTimeEvent OR $starttime > $endTimeEvent){} else { n++; } } } } return $n; } Hi All, I need to subtract dates and display the number of days left. I have a 'Start' date and an 'End' date in DATETIME format in the DB. Not quite sure where to start. A simply start - end doesn't work . Start = 2011-11-01-00:00:00 End = 2011-11-30-23:59:59 Since it is now 2011-11-27, my output should equal 3. Any help is appreciated. Hi guys, I am trying to do a multidates events availability calender. The script below indicates todays date by highlighting an orange colour and also indicates the start and end date of the event highlighting grey colour on the two dates (The colour are link via css classes as shown). Code: [Select] //Today's date $todaysDate = date("d/m/Y"); $dateToCompare = $daystring . '/' . $monthstring . '/' . $year; echo "<td align='center' "; if($todaysDate == $dateToCompare){ echo "class='today'"; }else{ //Compare's the event dates $sqlcount = "select event_start,event_end from b_calender where event_start ='".$dateToCompare."' AND event_end='".$dateToCompare."'"; $noOfEvent = mysql_num_rows(mysql_query($sqlcount)); if($noOfEvent >= 1){ echo "class='event'"; } } It works ok i.e. if start date = 01/01/2012 and end date = 04/01/2012 both date will be highlighted with grey colour. However I want it to also highlight grey on the dates between the 1st and 4th to show that then anydates between the 1st and 4th are not available and this is when I'm stuck. Please guys I need help. Thanks Hi, I want to compare the tables from 2 mysql databases in a table. This is what I have: for($i=0;$i<$maxCount;$i++) { echo "<tr>"; // start row //fist data square if ($i < count($db1)) echo "<td>{$db1[$i]}</td>"; else echo "<td></td>"; echo "<td></td>"; // middle //last if ($i < count($db2)) echo "<td>{$db2[$i]}</td>"; else echo "<td></td>"; echo "</tr>"; // end row } that will put make a nice table for me to see. What I'd like to do next is have all identical sql tables lined up. So for e.g I have 2 arrays of table names that will look like this: Databse 1 Database 2 table1 table1 table2 table3 table4 table4 does that make sense? Also is there a more elegant way of scripting what I have? Can php be used to get two blog entries and compare them side by side, with a choice one which one to use. A bit like wikipedia has ? Not sure if there is a better way to do this, but I want to check whether the value in a Sticky Field is the same as what is in the Database. If what is in the Sticky Field is *exactly* what is in the Database, then the User didn't update that field, and so I would NOT do an UPDATE. Seem reasonable? Here is where I grab the value out of the Form... Code: [Select] // **************************** // Process Each Form Field. * // **************************** foreach($_POST['answerArray'] as $questionID => $response){ // Copy trimmed Form array to PHP array. $answerArray[$questionID] = trim($response); And here is where I grab the existing value in the Database... Code: [Select] // ******************** // Check for Answer. * // ******************** // Build query. $q1 = "SELECT response FROM bio_answer WHERE member_id=? AND question_id=?"; // Prepare statement. $stmt1 = mysqli_prepare($dbc, $q1); // Bind variable to query. mysqli_stmt_bind_param($stmt1, 'ii', $memberID, $questionID); // Execute query. mysqli_stmt_execute($stmt1); // Store results. mysqli_stmt_store_result($stmt1); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt1)==1){ // Answer Found. // Bind result-set to variable. mysqli_stmt_bind_result($stmt1, $currResponse); // Fetch record. mysqli_stmt_fetch($stmt1); So I guess I want to compare $answerArray[$questionID] against $currResponse and see if there are any differences?! What is the best way to do that? Any better ideas of how to check to see if the User made any changes to a field so I only do an UPDATE if there was actually a change? Thanks, Debbie how to compare date with current date let say $date="2010-10-08 2:00 PM" how can i compare $date with current date and get the result in days, hours, minutes and seconds thanks Hi, I am trying to write an SQL to XML converter, so so far I have all the records inputted into the db tables, and now I want to append a child, but I don't know how to compare current row's field value with the next row below it, specifically I want to check if a current row is parent of the next row. I have already got the XML to SQL function working (some bugs but for the most part it's working) So for eg: <?php $query=mysql_query("SELECT * FROM edge"); while($row=mysql_fetch_assoc($query) ) { if($row['target'] is parent of the next row), then append the next row as child of current row } ?> Table edge is one of the tables that hold target node/source(aka: parent) nodes. Any help much appreciated! Hi everyone! I've been looking for a solution, but i just can't find it anywhere... Ok, so the problem is: i have a database which looks something like this: user_id product_id score 14 . 235 . 79 23 . 235 . 32 53 . 665 . 21 14 . 235 . 90 5 . 675 . 45 This is step-by-step of what i need to do: 1. Select user - user_id =343 2. For user_id =343 select all products that he gave score to: product_id = 43 - score = 99 product_id = 12 - score = 56 product_id = 68 - score = 32 product_id = 124 - score = 67 3. Find all users that voted for the same products e.g.: for product_id = 43: user_id = 125 voted 93 points, user_id = 23 voted 56 points. 4. Calculate the difference between the score of user, so: for product_id = 43: user_id = 125 voted 93 points (99 - 93 =6 points of diff.) user_id = 23 voted 56 points (99 - 56 =43 points of diff.) return the results.... That's basically what i need to do. I still don't know the number of the users, or product, but it doesn't really matter - i just need to make it work. Ok, hope someone can help! Hi! I have a table called "Categories" Here is the structu id | Categories | ParentCategories 1 | Rings | Parent Category 2 | Pendants | Parent Category 3 | Ladies Rings | Rings 4 | Ladies Pendants | Rings 5 | Gents Rings | Gents 6 | Necklaces | Parent Category But Necklaces is one of those who is not going to have any subcategories or you can say, it is going to be a category by itself. So how can I construct a php statement to get data out of MySQL to determine that Necklaces is a Category which does not have subcategories. Please help ! Thank you ! - Xeirus. Hi! What should the code be if I get an IP address to a postback url and I want to find that member in my database who has that IP-address? The postback comes like this http://yoursite.com/postback.php?ip=xxx Please help I thought I was able to determine which DateInterval is greater the same as done with DateTime, however, either this is not true or I am doing something wrong. Please advise. Thanks! private function compareDateInterval(\DateInterval $dateInterval1, \DateInterval $dateInterval2):bool { $greaterThan = $dateInterval1 > $dateInterval2?'true':'false'; echo("test1: dateInterval1 > dateInterval2: $greaterThan\n"); $dateTimeNow = new \DateTimeImmutable; $dateTime1 = $dateTimeNow->add($dateInterval1); $dateTime2 = $dateTimeNow->add($dateInterval2); $greaterThan = $dateTime1 > $dateTime2?'true':'false'; echo("test2: dateTime1 > dateTime2: $greaterThan\n"); $timestampNow = $dateTimeNow->getTimestamp(); $timestamp1 = $dateTime1->getTimestamp(); $timestamp2 = $dateTime2->getTimestamp(); $greaterThan = $timestamp1 > $timestamp2?'true':'false'; echo("test3: timestamp1 > timestamp2: $greaterThan\n"); echo('$dateTimeNow => '.json_encode($dateTimeNow).PHP_EOL); echo('$dateInterval1 => '.json_encode($dateInterval1).PHP_EOL); echo('$dateInterval2 => '.json_encode($dateInterval2).PHP_EOL); echo("timestampNow: $timestampNow, timestamp1: $timestamp1, timestamp2: $timestamp2\n"); } <b>Warning</b>: Cannot compare DateInterval objects in <b>/var/www/app/src/Tools/PointTransitionHistory.php</b> on line <b>136</b><br /> test1: dateInterval1 > dateInterval2: false test2: dateTime1 > dateTime2: true test3: timestamp1 > timestamp2: true $dateTimeNow => {"date":"2020-08-23 15:06:24.454702","timezone_type":3,"timezone":"UTC"} $dateInterval1 => {"y":0,"m":0,"d":2,"h":14,"i":0,"s":0,"f":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":1,"days":2,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0} $dateInterval2 => {"y":0,"m":0,"d":11,"h":15,"i":0,"s":0,"f":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":1,"days":11,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0} timestampNow: 1598195184, timestamp1: 1597971984, timestamp2: 1597190784
I run an article directory. I was wondering how I could check an article that is currently pending review against published articles in our database. What I am looking to do is to place the content of the body in the pending article into a variable. That much is easy and I know how to do that. Then I would like to use that variable to compare against other content in our database and have it output a percentage of how close it is to any other article already published in our database. Any direction our guidance with this would be so greatly appreciated. Thanks! I need to compare several arrays...to narrow down a bunch of mysql selects. I can't figure out which of the array_diff, array_unique, array_merge options there are. I need to get an array of umpires (baseball), then compare that to the array of umpires that can work a given level, then compare that to the array of umpires that can work at that school, and finally compare that to the array of umpires who have asked for the day off. In the code below, all of the selects work...the echo's that are commented out printed out what I expected them to. I'm having a problem with the array comparisons at the end of this code: Code: [Select] <?php //connect to database $dbc = mysql_pconnect($host, $username, $password); mysql_select_db($db,$dbc); //get info of game $sql = "SELECT sport,home,day FROM games WHERE `game_id` = $_GET[game]"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $game_array = $row['sport']; $home_team_array = $row['home']; $game_day_array = $row['day']; } //list of all umpires in association $sql = "SELECT ump_id FROM ump_names WHERE '$_SESSION[association_id]' = `association_id`"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $name_array[] = $row['ump_id']; // echo "<br /><br />All Ump ID's Array = "; // foreach($name_array as $name_array_final) { // echo $name_array_final . "<br />"; // } } //get bad schools list $sql = "SELECT ump_id FROM bad_school WHERE '$_SESSION[association_id]' = `association_id` AND `school` = '$home_team_array' and `sport` = '$game_array'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $bad_school_array[] = $row['ump_id']; // echo "<br /><br />Bad School Array = "; // foreach($bad_school_array as $bad_school_array_final) { // echo $bad_school_array_final . ", "; // } } //get official list at this game's level $sql = "SELECT ump_id FROM ump_names WHERE `association_id` = '$_SESSION[association_id]' AND `$game_array` = '1'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $official_level_array[] = $row['ump_id']; // echo "<br /><br />Officials that can work this level of game = "; // foreach($official_level_array as $official_level_array_final) { // echo $official_level_array_final . ", "; // } } //get vacation list $sql = "SELECT ump_id FROM days_off WHERE '$_SESSION[association_id]' = `association_id` AND `day` = '$game_day_array'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $days_off_array[] = $row['ump_id']; // echo "<br /><br />Officials that are on vacation this day = "; // foreach($days_off_array as $days_off_array_final) { // echo $days_off_array_final . ", "; // } } //$first_step = array_merge($official_level_array, $name_array); $first_step = array_merge($official_level_array, $name_array); $first_step_part_2=array_unique($first_step); //$second_step = array_merge($bad_school_array, $first_step); $second_step = array_merge($bad_school_array, $first_step_part_2); $second_step_part_2=array_unique($second_step); //$third_step = array_merge($days_off_array, $second_step); $third_step = array_merge($days_off_array, $second_step_part_2); $third_step_part_2=array_unique($third_step); echo "These umpires are available for this game:<br />"; foreach ($third_step as $iamavailable) { echo "$iamavailable<br />"; } ?> This prints out: Quote 2 1 2 4 5 6 10 14 15 3 7 8 9 11 12 13 16 17 It should only print out 4, 5, 6, 10, 14, 15. What I want to do is: compare $official_level_array and $name_array...only keep those that are in $official_level_array. Then, compare that result with $bad_school_array...removing those in the $bad_school_array...and keeping the ones that are left. Then, compare that result, with $days_off_array...removing those in the $days_off_array...and keeping the ones that are left. Print out what's left... Where am I going wrong? I know the forum is supposed to be used to help with any code I have come up with but here's to taking a shot anyway: I am in need of creating a php script that will allow me to input two different XML files and upon pressing "go" will compare these two files and save only the differences to a new xml file. Thing is, I have no idea where to start. Are there any php functions that exist that I can use to do this? If not, cn someone help me create one? Would this be better handled in javascript? If so, how can I do so using a method similar to the above? Any kind of help would be greatly appreciated. Hi again everyone, I am trying to compare a php variable to the value of a row in mysql, but keep getting the following error: Code: [Select] Wrong perameter count for mysql_result() What syntax would I use to accomplish this? Here is my code: // connects to server and selects database. include ("../includes/dbconnect.inc.php"); // table name $table_name = "availability"; // split up date into 3 separate fields $date = "12/25/2010"; $date_split = explode("/", $date); $month = $date_split[0]; $day = $date_split[1]; $year = $date_split[2]; // check if earth room is already reserved $taken = "Reserved"; $sql = "SELECT earth_room FROM $table_name WHERE month='$month' AND day='$day' AND year='$year' LIMIT 1"; $result = mysql_query($sql) or trigger_error("A mysql error has occurred!"); $row = mysql_result($result); if($row == $taken){ echo "Room Already Reserved"; } else{ echo "Room Available"; } Thanks for the help, kaiman |