php - comparing two date - php

i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code.
the following code should run if the time is above 23:29 and less then 08:10...
$gettime="04:39"; // getting this from database
$startdate = strtotime("23:29");
$startdate1 = date("H:i", $startdate);
$enddate = strtotime("08:10");
$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
{
echo"ok working";
}
please help me in dis regard
thanks

Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc...
$gettime= strtotime("22:00"); // getting this from database
$startdate = strtotime("21:00");
//$startdate1 = date("H:i", $startdate);
$enddate = strtotime("23:00");
//$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= $startdate && $gettime <= $enddate)
{
echo"ok working";
}

You are comparing the string with a date.
$gettime is a string and you are comparing it with a time object.
You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.

Assuming you're receiving the time from the DB in a date format (and not as a string):
change:
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
to:
if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1))

For comparing times, you should use the provided PHP classes
The DateTime::diff will return an object with time difference info:
http://www.php.net/manual/en/datetime.diff.php

You may refer to PHP documentation about DateTime::diff function at their website http://php.net/manual/en/datetime.diff.php
You may also go through this stackoverflow question How to calculate the difference between two dates using PHP?

Related

delete hours, minutes and secconds in age Unix PHP?

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"));

How to check if a date I passed

I'm getting a issue where I can't compare two dates in the format dd/mm/yyyy to check if a date is passed or not. code:
$Today = date('d/m/Y');
$fakturaDate = DateTime::createFromFormat('Ymd', $retrieved_DPFDT3);
if ($fakturaDate < $Today ) {
$x+= $y;
}
I don't know if the format is the problem, but if I could use the current it you be much easier.
Your problem is in that you are comparing string date('d/m/Y') with DateTime object.
Just use DateTime for both dates (-;
$Today = new \DateTime();
$fakturaDate = DateTime::createFromFormat('Ymd', $retrieved_DPFDT3);
if ($fakturaDate < $Today ) {
$x+= $y;
}
Compare dates using php function
if(strtotime($fakturaDate) < strtotime($Today))
Try searching on how to compare dates in php.

Hiding a link depending on date in PHP

I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId

Comparing time in php from mysql time is not giving right result

Mysql table for hours(field type time):
opened closed
12:00:00 23:59:00
In php i need to check if the current time is between these two times.
FIrst i have converted php current server time into mysql time format
$cur_time = date('H:m A',$_SERVER['REQUEST_TIME']);
$cur_time = DateTime::createFromFormat( 'H:i A',$cur_time);
$cur_time = $cur_time->format('H:i:s');
Then i have compared the times-
if($cur_time > $biz_hours['opened'] && $cur_time < $biz_hours['closed'])
Note: $biz_hours is the array to fetch data from mysql table.
Printing the $cur_time is displaying 09:12:00 just now. But if caluse returning false. Here is the live site url: http://dsbangladesh.com/takeout-banani/b/10 . Please help me to find the problem.
The comparison you are using is a simple string comparison. Your best bet is to convert your data into timestamps first. Something like this:
$curTime = time();
$openTime = strtotime($biz_hours['opened']);
$closeTime = strtotime($biz_hours['closed']);
if($curTime > $openTime && $curTime < $closeTime)
{ ....
I've used time to get the current server time instead of the method you used. I've also used strtotime to convert the mysql time field into a timestamp.
if (time() > strtotime($biz_hours['opened']) && time() < strtotime($biz_hours['closed']))
<?php
$biz_o = new DateTime(date('H:i:s',strtotime($biz_hours['opened'])));
$biz_c = new DateTime(date('H:i:s',strtotime($biz_hours['closed'])));
$now = new DateTime(date('H:i:s'),strtotime($_SERVER['REQUEST_TIME']));
if($now > $biz_o && $now < $biz_c){
//You got me
}

check if datetime from sql is today

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
}

Categories