I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
}else{
}
What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.
Try this :
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
//I want to run some code here
}else{
}
Hope it helps !!!!
One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:
$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
// current hour
}
Timestamps are convenient because:
there is no need to take the format into account;
operations on numbers are usually faster;
the code looks cleaner.
Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49
<?php
$current_datetime = strtotime(date('Y-m-d H:i'));
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
echo 'something';
}else{
echo 'something else';
}
Output:
echo $current_datetime . '<br/>';
2016-10-17 09:19
echo $send_date .'<br/>';
2015-04-13 09:03
// result
something else
Related
I work on one project with PHP and Mysql and I need to calculate the ages but I need delete the hours, minutes and seconds part. Here is an example:
The date of birth 2018-03-06 17:35:00 but
I need 2018-03-06 00:00:00
Here is my code:
function FetchAgeCaduce($MaxDias=3){
$fechaInicial = time();//date("Y-m-d");
$fecha = date("d/m/Y",$FechaFinal);
$fechaInicial = strtotime("d/m/Y",$fecha);
for ($i=0; $i<$MaxDias; $i++)
{
$Segundos = $Segundos + 86400;
$caduca = time()+$Segundos;//date("D",time()+$Segundos);
$var = date("D",$caduca);
if ($var == "Sat")
{
$i--;
}
else if ($var == "Sun")
{
$i--;
}
else
{
$FechaFinal = time()+$Segundos;
}
}
return $FechaFinal;
}
How can I work on it to get the expected result?
The right way / The MySQL way:
Store your data as DATE in MySQL, not DATETIME. DATE itself is described here. It does not store time, so you'll always have 00:00:00 as default.
The less right way / The PHP way:
Jay, Zeus, Freaking, K. Reist. Learn to use DateTime already, stop using date! It's like every second question here and noone learns DateTime!
Use it!
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
The output:
2018-03-06 00:00:00
P.S. $FechaFinal on line 5 is not defined.
You can format the date on either the application or database layer.
Using MySQL
You can use MySQL DATE_FORMAT Function
to parse the date into the wanted format.
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') dob;
See DEMO on SQL Fiddle.
Using PHP
Say you don't want to format the date in the database layer, may be because you would need to use the time part in some other calculations. Use the date functions as illustrated below:
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
//getting the expected date from the formatted string
$formateDate = DateTime::createFromFormat('Y-m-d H:i:s', $dt->format("Y-m-d 00:00:00"));
Im having some bizarre results in regards to the php date() function. Basically Im getting a date from a Mysql database which is in a string format, split into three elements. This would be Day, Month, Year (15 september 2012 for example) Im ultimately comparing two dates to see if it has expired. But the issue is that only certain dates are allowing the code to work, and some do not work at all (or allow the if statement to work effectively) Below is my code, any help would be great.
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year'))) ;
if ($expire < $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
Im sure its something simple, but for some reason I cannot solve it.
You need to compare the Unix timestamps.
$today = time();
$expire = strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year')) ;
if ($expire > $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
It looks like strtotime is expected a US date format; you need to swap the month and the day around to generate a valid date:
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_month')."-".
$this->getData('date_day')."-".$this->getData('date_year'))) ;
On the other hand, see Stephen305's answer - it's a much better solution to your problem.
I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.
In my PHP application I'm trying to compare date time values like the following:
if($datetime_from_db < date('Y-m-d H:i:s'))
{
// then do something
}
Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.
Comparing a string like "2011-02-14 15:46:00" to another string doesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:
strtotime($datetime_from_db) < time()
If you want this to work with dates past 2038, you can't use strtotime() or time().
See this question for the explanation.
A better approach:
new DateTime($datetime_from_db) < new DateTime();
This may help you.
$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);
if (strtotime($expectedDate) > strtotime($today)) {
echo "Expected date is greater then current date";
return ;
} else
{
echo "Expected date is lesser then current date";
}
Here is a solution where we use strtotime. I give two examples.
First one comparing the whole timestamp. Second one is just compare the date.
<?php
$date = "2022-10-06 17:49:10"; // string. can set any current timestamp
#example 1 - compare the date and time Y-m-d H:i:s
if(date("Y-m-d H:i:s" , strtotime($date)) >= date("Y-m-d H:i:s")){
echo "the date checked is bigger than today";
}else{
echo "the date checked is smaller than today";
}
#example 2 - compare the date only Y-m-d
if(date("Y-m-d" , strtotime($date)) == date("Y-m-d")){
echo "same day is true";
}else{
echo "same day is false";
}
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
}