check date in php not working with different month - php

here i am checking the date with current date to previous date it show the proper message when the subtracted date's result is current date .but when the subtracted result is previous date like 02-12-2014 - 4 days it gives 28-11-2014 .and condition of (02-12-2014>=28-11-2014) it gives false.why it cant check the diff of diff month's date. even it true the condition when date like (04-12-2014>=06-12-2014).
<div class="box-content">
<div class="maq_cont">
<marquee direction="up" scrollamount="3" onMouseOut="this.setAttribute('scrollamount',3,0)" onMouseOver="this.setAttribute('scrollamount', 0, 0)" style="height:200px; margin-top:-10px; margin-bottom:-10px;">
<ul class="maq_li">
<?php
echo $work_date = "03-12-2014";
echo "<br>";
echo $day = "3";
echo "<br>";
echo $show_date = date( "d-m-Y", strtotime( "$work_date -$day day" ));
echo "<br>";
echo $cur_date= date( "d-m-Y" );
if ($cur_date >= $show_date) {
echo '<li>done</li>';
} else {
echo '<li>not done</li>';
}
?>
</ul>
</marquee>
</div>
</div>

Try with -
if(strtotime($cur_date)>=strtotime($show_date)){
It is happening because they are strings.

You have to put the year at the beginning of your date string, then month and then the day. The reason is: You aren't comparing dates, you compare string. And they will be compared alphabetically.
e.g. the string date '01.01.2015' is alphabetically smaller than '02.01.2013', but this format ('Ymd') does the trick in this special order: '20150101' is alphabetically and also numerically greater than '20130102'.
// this formatting will work
$show_date = date('Ymd', strtotime("$work_date -$day day"));
$cur_date = date('Ymd');
I would prefer to do this comparison with date and the awesome DateTime object. Do it like this:
if (new DateTime('NOW')
>= DateTime::createFromFormat('d-m-Y', $show_date))
{
echo '<li>done</li>';
} else {
echo '<li>not done</li>';
}
The DateTime::createFromFormat() call returns a DateTime object. The first parameter $format has the same syntax like your format string you are using with date(). The second parameter is the so formatted date string to parse. Read more:
http://php.net/manual/en/datetime.createfromformat.php
After getting this DateTime object you can do some magic like
$date = DateTime::createFromFormat('d-m-Y', $show_date);
$date->modify('+1 days'); // one day later
And to output the date as string use the format()function:
$date->format('Y'); // the year
$date->format('m'); // the month
$date->format('d'); // the day
$date->format('Y-m-d H:i:s'); // e.g. 2014-12-05 23:11:00
$date->format('U'); // as timestamp: 1417817460
// [...]
More Information:
http://php.net/manual/en/datetime.format.php
http://php.net/manual/en/datetime.modify.php
http://php.net/manual/en/function.date.php

Related

PHP Date conversion date_create_from_format() not returning expected result

I have a string: 30/06/18 (30th June 2018)
I am converting to a date:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result: 18-06-2018
Now I want to add 20 days to the date:
$expiryDate = date("d-m-Y", strtotime("+20 days", $calcFieldDate));
echo $expiryDate;
Expected Result: 08-07-2018
Actual Result: 31-01-1970
I am obviously creating a date format which is then subsequently being treated as a string...
Every time I try a conversion, I just hit another road block - is there anyway to create a date that is then treated like a date?
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result:30-06-2018
$expiryDate = date("d-m-Y", strtotime("+20 days", strtotime($calcFieldDate)));
echo $expiryDate;
Result:20-07-2018
Strtotime() The second parameter is the timestamp
You actually don't need to revert using strtotime and date functions, you can actually use DateTime to simply add dates into it:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18');
echo $calcFieldDate->format('d-m-Y'); // get inputted date
$expiryDate = clone $calcFieldDate; // clone the original date object
$expiryDate->modify('+20 days'); // adjust the cloned date
echo $expiryDate->format('d-m-Y'); // show the adjusted date
This will sort your problem.
$str="30/06/18 (30th June 2018)";
$arr_temp=explode(" ",$str);
$str_date=str_replace("/","-",$arr_temp[0]);
$dt = DateTime::createFromFormat('d-m-y',$str_date);
$date=$dt->format('d-m-Y');
$new_date=date('d-m-Y',strtotime("+20 days",strtotime($date)));
echo $new_date;

converting a string to date in php

I have a string that contains date and time. Format of my string is yyyymmddtime.
For example. 20171125123000209. this is my complete string in which first comes the month, then month and then day after that time. How can i retrieve date from it by converting to readable date format. I tried with php's date function. But the output was not as expected. Please help.
Try this
<?php
$str_date= "20171125123000209";
$exiting_date_format='Ymd';
//first 8 characters from given date string in second parameter below
$date = DateTime::createFromFormat($exiting_date_format, substr($str_date,0,8));
echo $date->format('Y-m-d');//specify desired date format
?>
Output :
2017-11-25
DateTime::createFromFormat - Parses a time string according to a specified format
You can use date() function of php
<?php
$full_date= "20171125123000209";
echo date('dS F h:i:s A', $full_date);
//Output = 31st May 12:30:09 AM
?>
Or,
To get date from timestamp like now,
$timestamp= time(); //Or your timestamp here
$date = date('d-m-Y', $timestamp); //Inside first parameter, give your date format
echo $date; //17-12-2017
Or,
To get anything from string you can also use substr() function of php.
<?php
$full_date= "20171125123000209";
$year = substr($full_date, 0, 4);
$month = substr($full_date, 4, 2);
$date = substr($full_date, 6, 2);
echo 'Year = '.$year.' ';
echo 'Month = '.$month.' ';
echo 'Date = '. $date.' ';
?>
Output:
Year = 2017 Month = 11 Date = 25
Test in jdoodle
About substr() function in php
It's not necessary to manipulate the string at all. PHP's DateTime class supports parsing a string containing miliseconds natively, using the u format modifier:
$str = '20171125123000209';
$date = DateTime::createFromFormat('YmdHisu', $str);
Using your new $date object, you can convert to whatever format you're looking for, e.g.
echo $date->format("F j Y, g:i a");
// November 25 2017, 12:30 pm
See https://eval.in/920636
$your_strtotime_val = ""; //20171125123000209
$convert_to_date = date("m-d-Y h:i:s",$your_strtotime); // [m-d-Y h:i:s] this depending on how you convert date in first time so be careful

PHP Checking if outputted date is less than current date

I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';

PHP date comparison (2 weeks)

$todaysDate = date("Y-m-d");
$maxBookingDate=strtotime('+2 weeks', $todaysDate);
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST["Date"]);
$tableDate =$dateEntered->format('Y-m-d');
if ($tableDate < $todaysDate){
echo "Date must be in the future";
}
if ($tabledate > $maxBookingDate){
echo "Date must be no more than 2 weeks in advance";
}
Date comparison to make sure that the date a user enters is no more than two weeks in advance isn't working, what have I done wrong?
You can just use DateTime classes all through out so that its easier to compare:
$todaysDate = new DateTime();
$maxBookingDate = new DateTime('+2 weeks');
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST['Date']);
if ($dateEntered < $todaysDate){
echo "Date must be in the future";
} elseif ($dateEntered > $maxBookingDate){
echo "Date must be no more than 2 weeks in advance";
}
In your code:
$todaysDate is a string, and you fed it inside strtotime() as your second parameter which is incorrect usage. The second parameter requires numeric value (timestamp).
Inside your if else statement, you're comparing strings. You should be comparing them as timestamps or DateTime objects instead, like the answer above.

PHP Compare datetime values

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

Categories