PHP Datetime check date with different format - php

I've got a problem with datetime condition checked.
First, I've a DateTime value that stored in database as 2018-05-08 15:54:40
But, I want to check only date is equal or not.
For example:
$DateInDatabase = 2018-05-08 15:54:40
$DateSpecific = 2018-05-08
if ($DateInDatabase == $DateSpecific) {
......
}
The question is how to check only date in $DateInDatabase

If you are only interested in the year-month-day, my suggestion would be something such as;
// As per comments, the second param in the date function MUST be a UNIX timestamp, so strtotime will resolve this
$dateInDB = date("Y-m-d", strtotime($DateInDatabase)); // format to XXXX-XX-XX
$dateToCheck = date("Y-m-d", strtotime($DateSpecific)); // format to XXXX-XX-XX
if ($dateInDb == $dateToCheck)
{
// They are the same
}
else
{
// The are different
}
As others have said, you can use direct string comparison also;
$DateInDatabase = "2018-05-08 15:54:40";
$DateSpecific = "2018-05-08";
// This function uses the params haystack, needle in that order
if (stristr($DateInDatabase, $DateSpecific))
{
// Match found
}
else
{
// No match found
}

You can use php date method to format date:
$DateInDatabase ='2018-05-08 15:54:40';
$DateSpecific = '2018-05-08';
if (date('Y-m-d', strtotime($DateInDatabase)) == $DateSpecific) {
echo 'ok';
} else {
echo 'not ok';
}
Read more about php date method from here

You can either directly match as string or parse as date and later format as string.
Given that $DateInDatabase = '2018-05-08 15:54:40' and $DateSpecific = '2018-05-08'
if (false !== strpos($DateInDatabase,$DateSpecific)) {
/* matched */
}
OR
$format = 'Ymd';
$DateInDatabase = (new DateTime($DateInDatabase))->format($format);
$DateSpecific = (new DateTime($DateSpecific))->format($format);
if ($DateInDatabase === $DateSpecific) {
/* matched */
}

This will check if your dates are equal. Be aware that PHP's date function has a limit in how far you can go for the year. The minimum is 01-01-1970 and the maximum is 19-01-2038 (d-m-Y format used here). The date is converted to an integer (strtotime). If those numbers are equal, the dates are equal.
$DateInDatabase = '2018-05-08 15:54:40'
$DateSpecific = '2018-05-08'
$newDate1 = date("Y-m-d", strtotime($DateInDatabase));
$newDate2 = date("Y-m-d", strtotime($DateSpecific));
if ($newDate1 == $newDate2) {
//equal
} else {
//not equal
}

Related

Php dates is not compare properly

I am new in PHP
when I am trying to do this
if( date('m-Y',strtotime('2016-11-01 00:00:00')) < date('m-Y') ) {
echo "yes";
} else {
echo 'no';
}
but it always do false [output 'no'].
I must need to compare months is less than current month , means compare date do not have same months
where I am wrong to compare that date ?
Use DateTime to compare dates:
$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();
if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
echo 'yes';
} else {
echo 'no';
}
I copied your program so that it reads:
<?php
$x=date('m-Y',strtotime('2016-11-01 00:00:00'));
echo "$x\n";
$y=date("m-Y");
echo "$y\n";
if ($x < date('m-Y') ) {
echo "yes";
} else {
echo 'no';
}
On running it the output is:
# php x.php
11-2016
01-2017
no
That is why it fails. If you are checking for just the month you need to check for equality. Otherwise you need to reorder the date formatting to be "Y-m" (not 'm-Y') for less/greater than comparisons. Comparing the strings is fine.
date function always return a string. In your if construct you compare two strings. For current time:
"11-2016" < "01-2017"
In this case "11-2016" greater than "01-2017".
It will be better to use DateTime class.
$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();
if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
echo 'yes';
} else {
echo 'no';
}
or in your example you need to change format to 'Y-m'.
You should use a decent format to compare the dates. Instead of m-Y, use Y-m-d.
Currently, you are converting the dates to strings, with their months first. So the first date becomes 11-2016, the second becomes 01-2017. PHP compares these as strings, and finds that 0 is less thans 1, so considers the second string to be less.

Php custom date format and comparison

In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}

How to compare single date with multiple dates in PHP

How do i compare two dates in php?.
I have the following dates. One is coming from DB. and another is from Datepicker
$dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date
$datepickerDate = 06-06-2014 //Datepicker date.
Here $dbdate is in foreach loop and both formats are dd-mm-yyyy. How do i compare a single date from datepicker to the date in $dbdate?
Compare with STRTOTIME function in for loop like this
return STRTOTIME($dbdate) === STRTOTIME($datepickerDate);
best thing is convert all to unix time stamp..
php method is strtotime()
then it return integer value...u can compare that values
http://www.php.net//manual/en/function.strtotime.php
but the thing is ur dbdate parsing more than 1 date at a time..u should get 1 date at a time
This is not an ideal solution - but I hope it helps you out ;-).
<?php
// Input
$dbdate = '01-06-201402-06-201403-04-201405-06-2014';
$datepickerDate = '06-06-2014';
// Please note: it would be possible to check dates directly in this for loop.
// For educational purposes I splitted it.
$datepickerDateTime = strtotime($datepickerDate);
// Transform concatenated dates to separate dates in array.
$datesList = array();
$dateOffset = 10;
for($iCurrentDateOffset = 0; $iCurrentDateOffset < strlen($dbdate); $iCurrentDateOffset += $dateOffset) {
$datesList[] = substr($dbdate, $iCurrentDateOffset, $dateOffset);
}
// Compare each separate date to $datepickerDate
foreach($datesList as $date) {
if(strtotime($date) < $datepickerDateTime) {
echo("$date is before $datepickerDate<br />");
} else if(strtotime($date) == $datepickerDateTime) {
echo("$date is equal to $datepickerDate<br />");
} else if(strtotime($date) > $datepickerDateTime) {
echo("$date is past $datepickerDate<br />");
}
}
// ...
Output is:
01-06-2014 is before 06-06-2014
02-06-2014 is before 06-06-2014
03-04-2014 is before 06-06-2014
05-06-2014 is before 06-06-2014

Formatting partial unknown dates with DateTime() from a database?

I have a database that has a few unknown months or days formatted like so: 1999-01-00 / 1999-00-00.
Now, I've been using DateTime() to format the days that are full, which works fine.
I'd like to have abbreviations for unknown days, but known months using $DateTime->format('M Y'); which outputs Sep 1999
and
$DateTime->format('Y'); for 1999 that is for unknown months and days.
DateTime() Doesn't allow 00 values for months/days, so what are some ways to get around this?
Just what I was looking for (and didn't want to hear).
Here's a basic php function for those of you who are lazy like me.
function formatDatabaseDate($date, $delimiter = '/')
{
// this function works only on mysql date fields,
// and takes into account partial dates.
if ($date != '' && $date != NULL)
{
$datePieces = explode('-', $date);
if (count($datePieces) == 3 &&
strlen($datePieces[0]) == 4 &&
strlen($datePieces[1]) == 2 &&
strlen($datePieces[2]) == 2)
{
$datestring = '';
$months['01'] = 'Jan';
$months['02'] = 'Feb';
$months['03'] = 'Mar';
$months['04'] = 'Apr';
$months['05'] = 'May';
$months['06'] = 'Jun';
$months['07'] = 'Jul';
$months['08'] = 'Aug';
$months['09'] = 'Sep';
$months['10'] = 'Oct';
$months['11'] = 'Nov';
$months['12'] = 'Dec';
if ($datePieces[2] != '00' && $datePieces[1] != '00')
{
$datestring = $datePieces[2] . $delimiter
. $months[$datePieces[1]] . $delimiter
. $datePieces[0];
}
else if ($datePieces[1] != '00')
{
$datestring = $months[$datePieces[1]] . $delimiter
. $datePieces[0];
}
else
{
$datestring = $datePieces[0];
}
return $datestring;
}
else
{
trigger_error('date is not in a valid mysql format');
return false;
}
}
else
{
trigger_error('empty date passed to format command');
return false;
}
}
Unfortunately, the DateTime class is pretty much a wrapper for a UNIX timestamp. (I said pretty much, I know there's more to it than just that.) The way that it works with dates were one of the elements is zero is simply to calculate it as a synonym for the previous period. (e.g.: April 0 is calculated to become March 31.)
Really, you just have to bypass PHP's built in date functionality and write your own. The good news is that you can indeed do this. MySQL will actually return values as simple strings, and, when it comes to dates, the natural response that the actual C libraries use is to return the date pretty much as an ISO 8601 string. (There's that phrase pretty much again.)
If I were writing this, I would read the value raw with mysql_fetch_row (or your own method) and check if all the elements (i.e.: year, month, day) are defined. If they are, use the DateTime method. If not, I would write a piece of code to pull apart the elements that are defined and format it accordingly.

modifying date with php

Basically that is the function that I use to extract the date from the php and modify it:
function getAge()
{
$result= mysql_query("SELECT date_of_birth
FROM controlpanel
WHERE user_id=".$this->userID) or die(mysql_error());
$year="";
if($row=mysql_fetch_array($result))
{
$row['date_of_birth'];
}
}
$row['date_of_birth']; I want to get the year from that row, and check if it is 0000..if it is I want to return return "Not given";.. if it isnt, I want to compare the full date d-m-y to todays date.. in order to get the persons birth date..however, I am not sure what date functions to use..
if( substr($row['date_of_birth'],0,4) == "0000") echo "Not given";
$year = date("Y", $row['date_of_birth']);
if ($year == 0000) {
return "Not given";
}
return date("d m Y", $row['date_of_birth']);
this will give you the 4 digit year from your result:
$year = date('Y', strtotime($row['date_of_birth']);
then, you can use a function like the one on the following page to get the age:
http://www.geekpedia.com/code79_Calculate-age-from-birth-date.html
or other solutions:
http://www.google.com/search?gcx=w&sourceid=chrome&ie=UTF-8&q=php+get+age+from+birthday
need to add some quotes to declare the 0000 as string cause if you use 0000 not "0000" php will just read it as 0
$year = date("Y", $row['date_of_birth']);
if ($year == "0000") {
return "Invalid year";
}
else{
return "Valid year";
}

Categories