Check if a Date is in Past - php

I am getting Values out of a MySQL Table and my Date looks like: DD.MM
Now I want to check if this Date is in the past. I tried it with if($ende < date("d.m")); but it deleted values like 01.11 at the 23.10.
I need to remove entries that are in the past.
My Code Looks like:
if($ende < date("d.m")) {
$sqls = "DELETE FROM hausaufgaben WHERE Ende='$ende';";
if(!mysqli_query($conn, $sqls)){
echo "<p>Es gab keine älteren Hausaufgaben</p>";
}
}

Split the date so that it is in two parts, then compare the day and month seperately
$ende = "01.11";
$ende_split = explode( '.', $ende );
$ende_tag = $ende_split[0];
$ende_monat = $ende_split[1];
if( ($ende_tag < date('d')) && ($ende_monat <= date('m')) ){
$sqls = "DELETE FROM hausaufgaben WHERE Ende='$ende';";
if(!mysqli_query($conn, $sqls)){
echo "<p>Es gab keine älteren Hausaufgaben</p>";
}
}
monat uses <= because the month can be the same, but the day can be in the past.

You will need to use Str_To_Date() function, to convert your DD.MM format string to MySQL Date format (YYYY-MM-DD).
Since you mentioned that there will be data only from the current year; I can safely assume that the year is 2018 (It can be made generic by using YEAR(CURDATE()).
Try the following query instead:
DELETE FROM hausaufgaben
WHERE STR_TO_DATE(CONCAT(Ende, '.', YEAR(CURDATE())),
'%d.%m.%Y') < CURDATE()
Additional Details:
%d Day of the month as a numeric value (01 to 31)
%m Month name as a numeric value (00 to 12)
%Y Year as a numeric, 4-digit value

Related

Wordpress show different element if current date is two between dates

There are 4 seasons in my Wordpress template. Each season has a start and end date.
This is my current date:
$currentDate = date('d-m') . '-' . date('Y');
$currentDate = date('d-m-Y', strtotime($currentDate)); //output 16-05-19
Example of season 1 start and end date:
$season_1_start = get_sub_field('start_date','option');
$season_1_start = date('d-m-Y', strtotime($season_1_start));
$season_1_end = get_sub_field('end_date','option');
$season_1_end = date('d-m-Y', strtotime($season_1_end));
The output of the season dates is also 'd-m-Y'.
How can I check if $currentdate is between $season_1_start and $season_1_end
So:
if (($currentDate >= $season_1_start) && ($currentDate <= $season_1_end)){
echo "season 1";
}
if (($currentDate >= $season_2_start) && ($currentDate <= $season_2_end)){
echo "season 2";
}
if (($currentDate >= $season_3_start) && ($currentDate <= $season_3_end)){
echo "season 3";
}
if (($currentDate >= $season_4_start) && ($currentDate <= $season_4_end)){
echo "season 4";
}
But my output is season 1season 2season 3season 4
So it seems that every if statement is true.
I've already checked if the season dates are correct and I don't see anything wrong with them.
The result should be, today, season 2
I'm not well versed with WordPress, but seems like something you can easily solve in plain PHP.
You can use the DateTime class to compare against the current date today. Since your format isn't standard, we can use DateTime::createFromFormat(). This creates a DateTime object based on the format you provide - which in your case is d/m. Since no year is specified, it uses the current year.
You might need to adjust the conditions to >= or <=, depending on what dates your ranges are defined within.
$today = new DateTime;
$season_1_start = DateTime::createFromFormat("d/m", get_sub_field('start_date','option'));
$season_1_end = DateTime::createFromFormat("d/m", get_sub_field('end_date','option'));
if ($today > $season_1_start && $today < $season_1_end) {
// Season 1
}
Then do the same for your other seasons.

php get last year range date

I have a user in a database with a creation_date. This user can run a job in my app UI, but he is limited by a number of job to run in one year.
This user has been created in 2014. I would like to do something like :
function runJob($user){
$nbRemainingJob = findReminingJobs($user);
if ($nbRemainingJob > 0){
runJob($user);
}
else {
die("no more credits";)
}
}
findReminingJobs($user){
$dateRangeStart = ?; //start date to use
$endRangeStart = ?; //end date to use
$sql = "SELECT count(*) FROM jobs WHERE user_id=?";
$sql .= "AND job_created_at BETWEEN ($dateRangeStart AND $endRangeStart)";
$res = $pdo->execute($sql, [$user->id]);
$done = $res->fetchOne();
return ($user->max_jobs - $done);
}
Every user's creation birthday, the $user->max_jobs is reset.
The question is how to find starting/ending date ? in other words, I would like to get a range of date starting from the user's creation date.
For example, if the user was created on 2014-04-12, my start_date should be 2018-04-12 and my end_date = 2019-04-11.
Any idea ?
First get the user register date from db and split it into Year, Month and Day like
$register= explode('-', $userCridate);
$month = $register[0];
$day = $register[1];
$year = $register[2];
Then get the current year like
$year = date("Y");
$dateRangeStart = $year."-".$month."-".$day; //start date to use
Now, check if this date is greater then today date, then use last year as starting date
$previousyear = $year -1;
$dateRangeStart = $previousyear ."-".$month."-".$day; //start date to use
$endRangeStart = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dateRangeStart))
. " + 365 day"));
It is a idea, check if it work for you.
function getRange($registrationDate) {
$range = array();
// Split registration date components
list($registrationYear, $registrationMonth, $registrationDay) = explode('-', $registrationDate);
// Define range start year
$currentYear = date('Y');
$startYear = $registrationYear < $currentYear ? $currentYear : $registrationYear;
// Define range boudaries
$range['start'] = "$startYear-$registrationMonth-$registrationDay";
$range['end'] = date("Y-m-d", strtotime($range['start'] . ' + 364 day'));
return $range;
}
And for your example:
print_r(getRange('2014-04-12'));
Array
(
[start] => 2018-04-12
[end] => 2019-04-11
)
print_r(getRange('2014-09-13'));
Array
(
[start] => 2018-09-13
[end] => 2019-09-12
)
$created='2025-04-12';
$date=explode('-',$created);
if($date[0]<date("Y")){
$newDate=date('Y').'-'.$date[1].'-'.$date[2];
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
else{
$newDate=$created;
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
echo 'starting date is: '.$newDate;
echo '</br>';
echo 'ending date is: '.$dateEnding;
This code will get the date you have and match it with the current year. If the year of the date you provided is equal or above the current year the start date will be your date and end date will be current date +1 year. Otherwise if the year is below our current year (2014) it will replace it with the current year and add 1 year for the end date. Some example outputs:
For input
$created='2014-04-12';
The output is :
starting date is: 2018-04-12
ending date is: 2019-04-12
But for input
$created='2025-04-12';
The outpus is :
starting date is: 2025-04-12
ending date is: 2026-04-12
The solution that match my need :
$now = new DateTime();
$created_user = date_create($created);
$diff = $now->diff($created_user)->format('%R%a');
$diff = abs(intval($diff));
$year = intval($diff / 365);
if ($year == 0){
$startDate=$created_user->format("Y-m-d");
}else{
$startDate=$created_user->add(new DateInterval("P".$year."Y"))->format("Y-m-d");
}
The problem was to define the starting date that is comprised in the one year range max from the current date and starting from the user's creation date.
So if the user's creation_date is older than one year, than I do +1 year, if not, take this date. the starting date must not be greater than the current date_time
thanks to all for your help

Finding the difference between 2 dates in PHP

I am using PHP, jQuery AJAX and HTML to create a timesheet system, for this the user needs to select 2 dates within 1 month of each other. The system as yet is working and shows (very limited) data.
BUT! When I actually select a date over the month limit (i.e. 2 months further than the start or another year after the start), it still shows the table with the data.
For this I have this check:
$dt1 = new DateTime($_REQUEST['startdate']);
$dt2 = new DateTime($_REQUEST['enddate']);
$diff = date_diff($dt1, $dt2);
// I have tried this the other way around and get the same result...
if($diff->m > 1 || $diff->y > 1)
{
print("<center><strong>Time between dates it too great<br />Please choose another date or time within a month of each other</strong></center>");
die();
}
The dates are passed by a jQuery datepicker object via AJAX, and the dates I use, for example, are passed as such:
11/14/2015 (start date) && 12/14/2015 (end date) - should show data
09/14/2015 (start date) && 12/14/2015 (end date) - should not show data but does
11/14/2015 (start date) && 12/14/2016 (end date) - should not show data but does
There is a check in place that sees if the dates given start before the other and this works, I have tried the same kind of thing for this check, but without success, this check is as such:
function CountDaysBetween($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "start date is in the future! <br />";
return;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days + 1;
}
}
Edit
Dates 2 or more months apart within the same year work, tested again and this is the case, but dates into the next year do not
In your first part of the php code, you have put this operator>, but the problem is it means, everything Smaller than 1, not everything that is smaller than one or equal to 1. The easy solution is to change the operators to >=; which means everything that is equal to 1 or smaller than 1.
The date_diff constructs in PHP suck monkeyballs. Far more practical is to use straight comparisons instead:
$dt1 = new \DateTime($_REQUEST['startdate']);
$dt2 = new \DateTime($_REQUEST['enddate']);
$dt1->add(new \DateInterval('P1M'));
echo ($dt1 < $dt2 ? 'Less' : 'More') . ' than a month';
Also please do not use $_REQUEST, it has potentially terrible security issues. You should use $_GET, $_POST or $_COOKIE according to what you explicitly expect.

show value if today is equal to or less then two weeks away php

I am looking to show the value startdate (value set in DB) if today is greater then or equal 2 weeks away then if value enddate (value set in DB) is equal to or greater then today hide the value.
So far I have:
$dateintwoweeks = strtotime('+2 weeks');
$dateintwoweeks = date("H:i:s:T");
if ( $dateintwoweeks >= $startdate) {
echo "Upcoming: {$startdate}";
I am not sure if I am on the right track or way off but I am not sure how I would complete the second part on hiding the value if enddate >+ today.
Try this
// get `time` of two weeks
$dateintwoweeks = strtotime('+2 weeks');
// convert string date to `time`
$timeStartDate = strtotime($startdate);
// check if `time` of two weeks greater than `startdate`
if ( $dateintwoweeks >= $startdate) {
echo "Upcoming: {$startdate}";
}
Basically u can do the same in mysql as-well
by using DATEDIFF(expr1,expr2) it returns a number .
SELECT startdate,enddate,DATEDIFF(startdate,enddate) from tableName

PHP: Start Date - End Date range parsing by month

Ok, I've got a logistical question here more so than coding one, but a code example/solution might answer both, so here goes...
If I have a form that I pass in PHP with start_date and end_date (full on m/d/Y format) and I need to print out a table of all entries in mysql database that fall in that range (so from m1/d1/Y1 to m2/d2/Y2) grouped by month, how would I even go about doing that in an elegant way?
For example, if I pass start_date = 5/20/2012, end_date = 7/31/2012, I need the resulting table to show results in this format:
May 2012 | June 2012 | July 2012
.... | .... | .....
where the first column for May 2012 would show results from an mysql query like
SELECT ... WHERE signup_date >= 5/20/2012 AND signup_date <= 5/31/2012
and June 2012 would similarly show:
SELECT ... WHERE signup_date >= 6/1/2012 AND signup_date <= 6/30/2012
etc
So I am looking for a way to parse the start and end date into an array of dates properly arranged from the starting day of the month until the last day of the month, and if the end_date is a few months later then cover all the other months in-between in full (from 1st til last of that month), so that I can cycle through them in a for/while loop? So something like:
[0]['start'] => '5/20/2012'
[0]['end'] => '5/31/2012'
[1]['start'] => '6/1/2012'
[1]['end'] => '6/30/2012'
[2]['start'] => '7/1/2012'
[2]['end'] => '7/31/2012'
Any ideas?
You should be do achieve this with mktime() . Sample code below.
<?php
$startDate = '05/20/2012';
$endDate = '07/31/2012';
$curMonth = date("m", strtotime($endDate)); //End Month
$curYear = date("Y", strtotime($endDate)); //End Year
$months = array();
$months[] = array('start' => "$curMonth/01/$curYear", 'end' => $endDate);
while ("$curMonth/01/$curYear" > $startDate) {
$monthEnd = date("m/d/Y", mktime(0, 0, 0, $curMonth, 0, $curYear));
$curMonth = date('m', strtotime($monthEnd));
$curYear = date('Y', strtotime($monthEnd));
$monthStart = ($curMonth/01/$curYear > $startDate) ? $startDate : "$curMonth/01/$curYear";
$months[] = array('start' => $monthStart, 'end' => $monthEnd);
}
print_r(($months));
?>
try this:
$date = '5/20/2012';
$dateStart = date("m/01/y", strtotime($date));
$start = date("Y-m-d", strtotime($dateStart));
$end = date("Y-m-d", strtotime($dateStart. '+ 1 month - 1 day') );
echo $start;
echo $end;
See my comments first for mysql db date format.
written a bit in pseudo language
$sql="SELECT * FROM ... WHERE `signup_date`>='2012-5-20' AND `signup_date`<'2012-5-31' ORDER BY `signup_date`";
$result=mysql_query($sql);
$month_year=array() //3-dimensional array $month_year[year][month][primary_key];
$month_index=-1;
while($row=mysql_fetch_assoc($result)){
// find $month_of_the_date AND $year_of_the_date
//find different months ,corresponding years, and db primary key and keep track in the $month_year array
}
for( all the years in the array ){
for(all the corresponding months of the year in the array){
//**EDIT:** you MIGHT need other loops and arrays to collect distinct years and corresponding months together
// show the records with the primary keys corresponding to that month and year
}
}

Categories