I have a table with a date field type date.
What I am trying to do is to do a comparison between the date from inside the table and the today date. If the date from the table is yesterday then insert the today date.
The thing I'm not sure about is how to insert the data in the database so I can make the comparison. here is what im thinking to do"
$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
$oldTime = $y['date'];
}
if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}
So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point.
Any ideas?
Thanks
You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT.
Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way:
date('Y-m-d', time())
or even better, to get the current date, you can use just this line:
date('Y-m-d')
To conclude, you can do the if in this way:
if( strtotime($oldTime) < strtotime(date('Y-m-d')) )
or even better:
if( strtotime($oldTime) < strtotime('now') )
To compare dates you can use strtotime($date); Where date can be a time(), mysql date or date('Y-m-d'); string
Related
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.
Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?
Example:
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
You can use something like this:
$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = round(($t1 - $t2) / 3600);
In MySQL, you can do date arithmetics:
update mytable
set mydatetime = now()
where mydatetime <= now() - interval 1 hour and id = ?
The where clause filters on record whose column mydatetimeis more than one hour old. You did not tell what you want to do , so I assumed an update query, that resets the date/time to the current date/time.
This assumes that you want to update the timestamp of a given record, not accross the whole table, hence condition id = ?, which you can adapt - or remove - for your use case.
Hello Schmaniel at first i think you should use Carbon()
https://carbon.nesbot.com/docs/ to get the right results. It's a great way to work with timeformats and timestamps.
$now = Carbon::now();
$dbtime = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:10:22');
$totalDuration = $now->diffForHumans($dbtime);
dd($totalDuration);
$currentDate = new DateTime();
$databaseDate = new DateTime($dateFromDatabase);
$interval = $datetime1->diff($datetime2);
Then you can check using the $interval variable
You can use mysql TIMESTAMPDIFF like this:
SELECT TIMESTAMPDIFF(HOUR,'2003-02-01','2003-05-01 12:05:55');
you can use one of the follwing units:
MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
QUARTER, or YEAR.
Say, I have 4 dates and the date today is 1/7/16:
1/7/16 1:06:02
1/7/16 8:01:24
1/8/16 7:02:23
1/6/16 3:12:34
How can I only pick 1/7/16 1:06:02 and 1/7/16 8:01:24.
What date function from PHP can I use to only get the date of today?
Thanks!
UPDATE:
This is being used as a MYSQL selector.
Example: $db->query("DELETE * FROM entry WHERE date='$today'");
How would this work? How can I get my MYSQL query to select only the dates for today?
UPDATE 2:
I've tried using curdate(), but the code is not working...
This is what I'm doing:
$db->query("DELETE * FROM entry WHERE date=curdate()");
What am I doing wrong?
LAST UPDATE: curdate() worked properly...
UPDATE: As MySQL query, you can do this as follows:
$db->query("DELETE * FROM entry WHERE DATE(date) = CURDATE()");
CURDATE() returns today's date.
If you want to do with php, see below to use the DateTime class.
$now = new DateTime;
$otherDate = new DateTime('2016-01-01'); // or e.g. 2016-01-01 21:00:02
// Setting the time to 0 will ensure the difference is measured only in days
$now->setTime( 0, 0, 0 );
$otherDate->setTime( 0, 0, 0 );
var_dump($now->diff($otherDate)->days === 0); // Today
var_dump($now->diff($otherDate)->days === -1); // Yesterday
var_dump($now->diff($otherDate)->days === 1); // Tomorrow
The answer by schellingerht is totally correct, but
$now = new DateTime;
should be this instead:
$now = new DateTime('Today');
That will ensure that the date from today with 0 hours and 0 minutes is selected. Otherwise the output could be Today even if the date is tomorrow.
Hope that helps!
Convert to timestamp and then format for only the date. Then compare to the same format of todays date:
var_dump(
date('Ymd', strtotime('1/7/16 1:06:02')) === date('Ymd')
);
Try using DATE() (http://www.w3schools.com/sql/func_date.asp). You don't need to convert your dates to a string - this is not efficient.
DELETE FROM yourTable WHERE DATE(yourDateField) = DATE(NOW)
You could compare today's date with Y-m-d format, with your date parsed with the same format.
$today = date('Y-m-d');
$otherdate = date('Y-m-d', strtotime('2022-02-02 16:00:26'));
if($today === $otherdate){
\\ your code for Today
} else {
\\ your code for not Today
}
I need to check with php if values got from a database are from last 30 days.
The values are formatted as follows:
2012-03-19 05:00:32
How can this be done?
You can use strtotime to turn it to a unix timestamp.
$db_date = "2012-03-19 05:00:32";
if (time() - strtotime($db_date) <= 30 * 86400) {
//...
}
$date = '2012-03-19 05:00:32';
if (strtotime($date) >= strtotime('-30 days')) {
// do something
}
See strtotime() reference.
You could do it in PHP, but that'd mean a roundtrip through the date/time system to process that string back into a date value:
$within_30 = ((strtotime('2012-03-19 05:00:32') + 30*86400) > time());
Assumign you're using MySQL, you could do it in the query directly, and save some time conversions:
SELECT ((yourtimefield + INTERVAL 30 DAY) > now()) AS within_30 ...
I have a problem getting certain data from my database by querying a date range. In my database i have a DATE type field within the format YYYY-MM-DD. I want to get all data within a date range of today + 2 weeks (Expiring).
I have wrote:
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
$today = date('Y-m-d');
$q = "SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'";
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}
So what I want to achieve is for the query to pull all the rows from now until 5th October. I've echo'd the variables and they show they're in the correct form (YYYY-MM-DD) to compare within the database but no results are returning.
Any help would be greatly appreciated. Many thanks in return.
Well, assuming that the mysql database has the same date that your server, you could let the mysql database do all the date calculations.
A little something like this:
SELECT *
FROM listing
WHERE dd_end BETWEEN CURDATE() AND (CURDATE() + INTERVAL 14 DAY)
On the other hand, i think Paul S's answer may fix your problem.
Edit:
You forgot to call mysql_query before the mysql_fetch_assoc() function.
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result))
{
$listing_id = $row['listing_id'];
echo "$listing_id";
}
If dd_end is a date you may want to read a certain section on the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
For best results when using BETWEEN with date or time values, use
CAST() to explicitly convert the values to the desired data type.
Examples: If you compare a DATETIME to two DATE values, convert the
DATE values to DATETIME values. If you use a string constant such as
'2001-1-1' in a comparison to a DATE, cast the string to a DATE.
May this is the right way ?
$start = date("Y-m-d", strtotime('+14 day' . $date));
Read:
http://php.net/manual/en/function.strtotime.php
strtotime has a second argument.
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
Should be:
$new = strtotime('+14 day', time());
$start = date("Y-m-d", $new);
$today = date('Y-m-d');
$q = mysql_query("SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'");
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}