I have a MySQL database with a list of dates. I want to output all these dates, provided they occur after today, into a page. The dates are stored in the database in DATE format, as Y-m-d.
I've got the following code (excluding the query etc):
$dateToday = date('Y-m-d');
do{
$dateCompare = new DateTime($row['date']);
if ($dateCompare > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
But this just outputs all the dates, including one I have set in the past for testing purposes. What am I doing wrong?
$dateToday is a string. $dateCompare is a DateTime object.
You should use strtotime() function.
http://www.w3schools.com/php/func_date_strtotime.asp
Try and convert the date from myssql to a datetime object and output.
$changetime = new DateTime($time, new DateTimeZone('UTC'));
ECHO $changetime->format('m/d/y h:i a');
// list of timezones http://us1.php.net/manual/en/timezones.php
I actually use this to output all my MYSQL datetime data - allows me to convert to any timezone. Note, this will assume your datetime is in UTC - you should convert to your timezone.
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach ($stmt as $row) {
$time = strtotime($row['date']);
if ($_SERVER['REQUEST_TIME'] - $time) {
echo '<p>'. date('Y-m-d', $time) . '</p>';
} else {
echo '<p>FALSE</p>';
}
}
Related
I have Id's I went to check if they have expired, they're in y/m/d format so I get todays date in that format and it comes out incorrect.
How can I compare
2021/03/15
With 2021-12-25
The dashes versus slashes doesn't seem to matter, so I think it's the month
Todays date is parsed as a date, the other is a string from an SQL statement array
$utz = new DateTimeZone($_SESSION['timezone']);
$dt = new DateTime(null, $utz);
$today = $dt->format('Y/m/d');
while($myrow = pg_fetch_assoc($result))
if ($myrow['id1_expiry'] < $today) {
printf ("<tr bgcolor=#FD5D5D>.... }else{
You could compare the DateTime objects using comparison operators.
You could use a formated date to create a new DateTime object, for accepted format.
$utz = new DateTimeZone($_SESSION['timezone']);
$date = new DateTime(null, $utz);
while ($myrow = pg_fetch_assoc($result)) {
if (new DateTime($myrow['id1_expiry'], $utz) < $date) {
echo 'expired';
}
}
I have an Oracle query which returns date string in the format Y-m-d H:i:s and I need to pass them to the Series::AddXY method. How can I do that?
The "CandleChart.php" example in the Features demo shipped with the product uses DateTimes on the horizontal axis.
Here a variation:
<?php
//Includes
include "../../../../sources/TChart.php";
$chart1 = new TChart(600,450);
$chart1->getChart()->getHeader()->setText("Candle Style");
$chart1->getChart()->getAspect()->setView3D(false);
// Clip Series points
$chart1->getChart()->getAspect()->setClipPoints(true);
$chart1->getChart()->getLegend()->setVisible(false);
// Add Candle data using doubles for date values
$today = time();
$day = 86400;
$hour = 3600;
$chart1->getAxes()->getBottom()->setIncrement(DateTimeStep::$ONEMINUTE);
$chart1->getAxes()->getBottom()->getLabels()->setDateTimeFormat('d/m/Y H:i:s');
$chart1->getAxes()->getBottom()->getLabels()->setAngle(90);
$candle=new Candle($chart1->getChart());
$chart1->setAutoRepaint(false);
for ($i=$today;$i<($today+$hour);$i+=60) {
$candle->addCandle($i,rand(0,100),rand(0,100),rand(0,100),rand(0,100));
}
$chart1->setAutoRepaint(true);
$chart1->doInvalidate();
$chart1->render("chart1.png");
$rand=rand();
print '<font face="Verdana" size="2">Candle Chart Style<p>';
print '<img src="chart1.png?rand='.$rand.'">';
?>
The problem is that I do not have constant time intervals and I can not use a "time machine" as in the Candle example .
The time (X value) I have comes from an Oracle query:
$query = "SELECT ptm.IDENTIFICACAO,
mtr.SERIAL,
TO_CHAR(rtu.DATAHORA, 'yyyy-mm-dd hh24:mi:ss') AS DATAHORA,
So the DateTime value is a string in the PHP date format : Y-m-d H:i:s, which I need to convert to TChart values. I do not know if I am full correct but it
seems that DateTime values should be entered as float values (Unix Timestamp)
So I am converting them as follows:
while( ($row = oci_fetch_array($stmt, OCI_ASSOC)) != false ){
$thetime = DateTime::createFromFormat('Y-m-d H:i:s', $row["DATAHORA"]);
if($thetime)
$tchart->getChart()->getSeries(0)->addXY((float) $thetime->getTimestamp() , $row["ENERTOT"] / 1000);
}
++$rowCount;
}
I hope this can help someone else.
Best regards.
I've created an If an Else Statement but it doesn't work properly.
I have some dates within my SQL which have been retrieved and stored in variables using PHP.
I'm comparing the current date with the dates from the database but for some reason, it thinks for example that 29-09-2015 if LESS THAN 31-01-2015.
I can understand that the format could be the issue d,m,Y but I thought I'd corrected that already.
Here's the code:
$today = date('d-m-Y');
$date = $row['respondby'];
$euDate= date("d-m-Y", strtotime($date));
<?php
if($today < $euDate){ echo "<td>". $today." is less than ". $euDate ."</td>";
}
else{
echo"<td>Lost somewhere in between ?!?!?! :S </td>";
}
?>
As a result it prints
29-09-2015 is less than 30-06-2015
today's date was 29-09-2015 and one of the dates was in the data was this one as shown.
Thank you everyone that helps.
Comparison of dates as strings uses lexicographical order, hence your result is "correct".
Instead of d-m-Y format, try to use Y-m-d, this guarantees proper ordering.
$today = date('Y-m-d');
$date = $row['respondby'];
$euDate= date("Y-m-d", strtotime($date));
if($today < $euDate) { [...] }
Or, you can use Date objects instead:
$today = new Date('now');
$euDate= new Date($row['respondby']);
if($today < $euDate) { [...] }
Thanks to the answers to this question, I've managed to only output a list dates from my MySQL database that are in the future (ie after today) using PHP. However, what if I wanted to set 'today' back a little; in other words, if I want a date not to appear on the list of dates a week in advance?
I've attempted to use DateTime::sub using the following code, but it kills my script (I just get a blank screen - if I comment out the DateTime::sub line, it works again. I still haven't worked out how to get PDO to echo error details):
$dateToday = new DateTime('now');
$dateToday -> sub(new DateInterval('P7D'));
do{
$dateCompare = new DateTime($row['date']);
if ($dateCompare > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
Any ideas?
You code works just fine for me, I imagine it's a problem with this line:
$dateCompare = new DateTime($row['date']);
What format is the $row's date in?
I'd recommend using
$date = DateTime::createFromFormat('The format your dates are in', $row['date']);
See http://www.php.net/manual/en/function.date.php for possible date formats
e.g. Y-m-d would parse 2012-10-28
If you have an older version of PHP, you could try this "low tech" solution by comparing as strings.
// Assuming your mysql is Y-m-d
$dateToday = date('Y-m-d')
do{
if ($row['date'] > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
while...
My $date output is in the foreach loop
09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10,
09/24/09, 02/19/09, 12/21/08
My mysql query(PHP) is as follows
("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");
Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.
I tried with date('Y-m-d H:i:s', $date); but no help.
Note: My database field is datetime type.
Any idea?
You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.
I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:
date('Y-m-d H:i:s', strtotime($date));
The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.
I created my own function for this purpose, may be helpful to you:
function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
if (!is_string($fromDate))
return null ;
try {
$DT = DateTime::createFromFormat($format, trim($fromDate)) ;
} catch (Exception $e) { return null ;}
if ($DT instanceof DateTime){
if (is_array($hms) && count($hms)===3)
$DT->setTime($hms[0],$hms[1],$hms[2]) ;
return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
}
return null ;
}
So in your case, you use format m/d/yy :
$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
//Ok, proceed your date is correct, string is returned.
}
You don't have the century in your date, try to convert it like this:
<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;
Prints:
2011-09-25
Now you can insert $date into MySQL.