PHP - Help With Date() And Mktime() Functions
New user of PHP here! I'm using it to display entries from my MYSQL database. Image below.
This is the code snippet that displays information from the 'name', 'author' and 'date' columns of my database. I learned this technique from w3schools. $result = mysql_query("SELECT * FROM levels ORDER BY date DESC"); while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['author'] . "</td>"; echo "<td align='right'>" . $row['date'] . "</td>"; echo "</tr>"; } I would like to use the date() function to format the date differently. But the date() function requires that I convert my time into a timestamp. I know you have to use the mktime() function for this, but I don't know how. Can someone show me how to pass the contents from $row[date] into the mktime() function? Similar TutorialsI'm practising how to do date and time in PHP. I wanted to see if I can get all of the date/time variables from user submission and format them correctly. I went with ISO 8601 date... // From the Manual: // date('c', mktime(1, 2, 3, 4, 5, 2006)); // Prints something like: 2006-04-05T01:02:03+00:00 ...but my attempts always produce a slightly different result for the year, month and timezone... Code: [Select] $inputTime = date('c', mktime((int)$timeHour, (int)$timeMins, (int)$timezone, (int)$dateMonth, (int)$dateDay, (int)$dateYear)); echo $inputTime; // Should return: 2013-11-02T02:30:01+00:00 // Instead returns: 2012-12-02T02:30:01-08:00 The timezone value coming from HTML... <option value="1.0">(GMT +1:00)</option> I noticed; 1. It always picks a year less than whatever year I select. 2. It always selects 12 as the month. 3. It always adds -08:00 after the picking the correct timezone. How come? Thanks in advance. Here is the code im using $dateOfBirth = ''; preg_match('|Born on ([a-zA-Z]*\s[0-9]*,\s[0-9]*)\\\u003c\\\/span>|', $page, $match); if($match && count($match)>0) { $date = str_replace(",","",$match[1]); blue($date); $timestamp = strtotime($date); $dateOfBirth = date('Y-m-d',$timestamp); // 1994-03-23 } else { red("No Age is set on profile"); continue; } im getting a match like this March 9, 1993 When i run my script im getting this error [2048] strtotime() [function.strtotime]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Chicago' for 'CST/-6.0/no DST' instead Error: [2048] date() [function.date]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Chicago' for 'CST/-6.0/no DST' instead What could be the problem?? I'm using microtime to capture $start_time and $finish_time bothing using microtime() function. I then pass both $start_time and $finish_time into date() function to parse a date. The difference between $start_time and $finish_time is also calculated. The problem being the date() function is producing incorrect values. list($total_count, $success_count, $errors_data, $start_time, $finish_time) = $summary_data; $duration_time = $finish_time - $start_time; echo "<b>Started Processing At:</b> ".date('m/d/Y H:i:m', $start_time)."<br/>"; echo "<b>Completed Processing At:</b> ".date('m/d/Y H:i:m', $finish_time)."<br/>"; echo "<b>Processing Duration:</b> $duration_time seconds<br/><br/>"; The output: Started Processing At: 11/22/2010 18:45:11 Completed Processing At: 11/22/2010 18:45:11 Processing Duration: 8.0499620437622 seconds Hello fellow php friends, Im having abit of trouble trying to echo out a statement at certain times of the day. for example how would you echo out 'Good Morning' between the times of 01am to 11.59am then echo out 'Good afternoon' between times of 12pm and 6pm and so on. Please help!!!!! My friend a I have to different numbers when we echo mktime(0,0,0,5,12,1990). How is this possible? I thought that only, we you leave some parameters blank, the local this is used, else, it's standardized. thanks in advance how do I use strtotime() instead of mktime()? $matchTimea = mktime($mHour, $mMinute, 0, $mMonth, $mDay, $mYear); if($matchTimea-time() < $cutoffTimea*60) { right now i have my date system to say "X amount of seconds ago, X hours ago, X days ago, X years ago, How could i turn mktime() (1290874161) into a mm/dd/yyyy format? so it would say like, "Nov 27, 2010 at Hour:Minute" (whatever the hour/minute is) I'm an extreme newbie and have this current error on my site. The error states: Warning: mktime() expects parameter 4 to be long, string given in featured_product.php on line 75 <?php for ($i = 0; $i < $num_rows; $i++) { $id = mysql_result($result,$i,"id"); $title = mysql_result($result,$i,"title"); $featured = mysql_result($result,$i,"featured"); $feature_date = mysql_result($result,$i,"feature_date"); $feature_date_arr = explode("-",$feature_date); $feat_date = mktime(0,0,0,$feature_date_arr[0],$feature_date_arr[1],2000+$feature_date_arr[2]); if ( ($feat_date+($featured*24*60*60))<time() ) { $db2->query("UPDATE product_catalog SET featured = 0 WHERE id='$id'"); $featured = 0; } else { $featured = 1; $db2->query("UPDATE product_catalog SET featured = 1 WHERE id='$id'"); } ?> Any ideas on how to correct this? Thanks! Or am I just going crazy? OK, I've been running a query that uses the snippet below to get the previous month. It's : Code: [Select] $sql = "SELECT COUNT(`id`) as `counted` FROM `click_tracking` WHERE `date` LIKE '". date('Y-m', mktime(0, 0, 0, (date('m')-1), date('d'), date('Y'))) ."-%'"; Here's a snippet for people to try: Code: [Select] date_default_timezone_set('America/Toronto'); echo date('Y-m', mktime(0, 0, 0, (date('m')-1), date('d'), date('Y'))); //prints 2012-03 (March, which is incorrect; should be February- 2012-02) That should have printed 2012-02, but instead, it prints 2012-03. If I modify the mktime() to (date('m')+1): Code: [Select] date_default_timezone_set('America/Toronto'); echo date('Y-m', mktime(0, 0, 0, (date('m')+1), date('d'), date('Y'))); //prints 2012-05 (May, which is incorrect; should be April - 2012-04) It prints 2012-05 which is incorrect for the given timezone. Should be 2012-04 I'm thinking it's a leap year bug and will work itself out tomorrow (per my timezone, anyways). So, when I use the mktime() function, it seems to be thinking we're in April already. A standard date('Y-m') prints the correct YYYY-MM (2012-03) though. Am I tripping out? Hi, I'm getting this error: Warning: mktime() expects parameter 5 to be long, string given in /home/user/public_html/include/functions.php on line 58 The code is: if($Date_Format == 1) #For dd-mm-yyyy { $Date_Output = date("d-m-Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 2) #For dd/mm/yyyy { $Date_Output = date("d/m/Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 3) #For mm-dd-yyyy { $Date_Output = date("m-d-Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 4) #For mm/dd/yyyy { $Date_Output = date("m/d/Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 5) #For Mon Day YYYY { $Date_Output = date("M D Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 6) #For Month Day YYYY { $Date_Output = date("F D Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 7) #For Date"nd" Month YYYY { $Date_Output = date("d\\t\h F Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 8) #For Month Day YYYY { $Date_Output = date("F d Y",mktime(0,0,0,$Month,$Day,$Year)); } elseif($Date_Format == 9) #For Month Day YYYY { $Date_Output = date("d/m/Y H:i",mktime($DateDispsplittimehr,$DateDispsplittimemin,0,$Month,$Day,$Year)); // Line 58 } return $Date_Output; } else { return NULL; Line 58 says $Date_Output = date("d/m/Y H:i",mktime($DateDispsplittimehr,$DateDispsplittimemin,0,$Month,$Day,$Year)); I really appreciate any help on this. I want to have a couple of different formats from mktime(), which the value could be: 1292183335. I would like to have some of the formats like: Tuesday at 12:00am, Wednesday, January 12, 2011 at 12:00am Also taking different timezones in consideration. I'm not sure what to use for that. I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; Hey, I'm using a script which allows you to click on a calendar to select the date to submit to the database. The date is submitted like this: 2014-02-08 Is there a really simple way to prevent rows showing if the date is in the past? Something like this: if($currentdate < 2014-02-08 || $currentdate == 2014-02-08) { } Thanks very much, Jack I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? Hello. I'm new to pHp and I would like to know how to get my $date_posted to read as March 12, 2012, instead of 2012-12-03. Here is the code: Code: [Select] <?php $sql = " SELECT id, title, date_posted, summary FROM blog_posts ORDER BY date_posted ASC LIMIT 10 "; $result = mysql_query($sql); while($row = mysql_fetch_assoc($result)) { $id = $row['id']; $title = $row['title']; $date_posted = $row['date_posted']; $summary = $row['summary']; echo "<h3>$title</h3>\n"; echo "<p>$date_posted</p>\n"; echo "<p>$summary</p>\n"; echo "<p><a href=\"post.php?id=$id\" title=\"Read More\">Read More...</a></p>\n"; } ?> I have tried the date() function but it always updates with the current time & date so I'm a little confused on how I get this to work. Alright, I have a Datetime field in my database which I'm trying to store information in. Here is my code to get my Datetime, however it's returning to me the wrong date. It's returning: 1969-12-31 19:00:00 $mysqldate = date( 'Y-m-d H:i:s', $phpdate ); $phpdate = strtotime( $mysqldate ); echo $mysqldate; Is there something wrong with it? I have tried a large number of "solutions" to this but everytime I use them I see 0000-00-00 in my date field instead of the date even though I echoed and can see that the date looks correct. Here's where I'm at: I have a drop down for the month (1-12) and date fields (1-31) as well as a text input field for the year. Using the POST array, I have combined them into the xxxx-xx-xx format that I am using in my field as a date field in mysql. <code> $date_value =$_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']; echo $date_value; </code> This outputs 2012-5-7 in my test echo but 0000-00-00 in the database. I have tried unsuccessfully to use in a numberof suggested versions of: strtotime() mktime Any help would be extremely appreciated. I am aware that I need to validate this data and insure that it is a valid date. That I'm okay with. I would like some help on getting it into the database. (continuing from topic title) So if I set a date of July 7 2011 into my script, hard coded in, I would like the current date to be checked against the hard coded date, and return true if the current date is within a week leading up to the hard coded date. How could I go about doing this easily? I've been researching dates in php but I can't seem to work out the best way to achieve what I'm after. Cheers Denno Hi, I have a job listing website which displays the closing date of applications using: $expired_date (This displays a date such as 31st December 2019) I am trying to show a countdown/number of days left until the closing date. I have put this together, but I can't get it to show the number of days. <?php $expired_date = get_post_meta( $post->ID, '_job_expires', true ); $hide_expiration = get_post_meta( $post->ID, '_hide_expiration', true ); if(empty($hide_expiration )) { if(!empty($expired_date)) { ?> <span><?php echo date_i18n( get_option( 'date_format' ), strtotime( get_post_meta( $post->ID, '_job_expires', true ) ) ) ?></span> <?php $datetime1 = new DateTime($expired_date); $datetime2 = date('d'); $interval = $datetime1->diff($datetime2); echo $interval->d; ?> <?php } } ?> Can anyone help me with what I have wrong? Many thanks Hi there, I have a string '12/04/1990', that's in the format dd/mm/yyyy. I'm attempting to convert that string to a Date, and then insert that date into a MySQL DATE field. The problem is, every time I try to do so, I keep getting values like this in the database: 1970-01-01. Any ideas? Much appreciated. |