I would like validate the current date with question posted date if date difference is greater then 1 day then it needs to show in over due question also this will not consider the array of dates which are already i having in my array.
Like if a question posted on 20-July-11.
exemption date array {'21-July-11', ... etc}
current date is 22-July-11
then the output needs to be shown like question is waiting for 1 day instead of 2 days.
can any one help on it.
That is some example code I have created for you to calculate the due date. When you submit a question, calculate the due date that way and store it in the database with entry for that question...
<?php
$daysDue = 2;
$exDatesArray = array("2011-07-21", "2011-07-23"); //array with all your holiday dates.
$question_1_Date = "2011-07-21";
$question_2_Date = "2011-07-18";
$question_3_Date = "2011-07-20";
echo "Holidays on: ";
foreach( $exDatesArray AS $exdate )
{
echo $exdate . ", ";
}
echo "<br/><br/>";
echo "submit date -> due date<br/>";
echo $question_1_Date . " -> " . calculateDueDate( $question_1_Date, $exDatesArray, $daysDue ) . "<br/>";
echo $question_2_Date . " -> " . calculateDueDate( $question_2_Date, $exDatesArray, $daysDue ) . "<br/>";
echo $question_3_Date . " -> " . calculateDueDate( $question_3_Date, $exDatesArray, $daysDue );
function calculateDueDate( $date, $exDates, $daysDue )
{
//start with day 1
$count = 1;
//now we loop from day one to due days
while( $count <= $daysDue )
{
//add one day to start date
$date = add_date( $date, 1 );
//check if that new date is a holiday
if( !in_array($date , $exDates) )
{
//only if it is not a holiday we increase counter, otherwise we dont count that day towards due period
$count++;
}
}
//return calculated due date
return $date;
}
function add_date($date,$days)
{
$cd = strtotime($date);
return date('Y-m-d', mktime(0,0,0,date('m',$cd),date('d',$cd) + $days, date('Y',$cd)));
}
?>
Output:
Holidays on: 2011-07-21, 2011-07-23,
submit date -> due date
2011-07-21 -> 2011-07-24
2011-07-18 -> 2011-07-20
2011-07-20 -> 2011-07-24
//convert date to unixtime (seconds)
$question_sec = strtotime($question);
//subtract
$diff = time() - $question_sec;
$days = $diff / 60*60*24;
echo "$days old";
Related
// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if ($chkDateYoil == 6) {
// Saturday when + 2
$timestamp = strtotime($chkDate . " +2 days");
$chkDate = date("Y-m-d", $timestamp);
} else if ($chkDateYoil == 0) {
// Sunday when + 1
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
}
// If it's a weekday, compare it array
foreach ($holy as $key => $holyday) {
if ($chkDate == $holyday) {
// holiday when + 1
$day_plus = 8 - $chkDateYoil;
$timestamp = strtotime($chkDate." +".$day_plus." days");
$chkDate = date("Y-m-d", $timestamp);
}
}
return $chkDate;
}
Hello, let me ask a question.
The following codes are:
Is the input value weekend?
Or are they included in the array?
in accordance with the judgment
Weekday extraction code.
But there is an error.
in my estimation
December 30th is supposed to come out.
By the way, January 2, 2021 is the result.
Why is that?
sorry
i don't write english very well
Thank you for reading.
The problem is in this line: $day_plus = 8 - $chkDateYoil;, which is calculating the date of the next Monday the first time it's executed.
You're then looping through the rest of the $holy array, and updating $chkDate if necessary, but you're not recalculating the value of $chkDateYoil, so the output depends on the day of the week you run this. Today (23rd December) it stops on 2nd January
Your code can be simplified by just incrementing the date by 1 day and performing the checks again, continuing until you get a result. I've also used the PHP function in_array() to simplify the search of the $holy array, and incorporated it into the same test as Saturday and Sunday.
// holiday array
$holy = [
'2020-12-23',
'2020-12-24',
'2020-12-25',
'2020-12-28',
'2020-12-29',
];
$inputDate = '2020-12-23'; // input
$outputDate = get_date($inputDate);
echo "Winning Day: " . $outputDate . "<br />";
echo "<br />";
function get_date($chkDate)
{
global $holy;
do {
$chkDateYoil = date("w", strtotime($chkDate)); // sat(6), sun(0)
if (($chkDateYoil == 0) || ($chkDateYoil == 6) || (in_array($chkDate, $holy))) {
$timestamp = strtotime($chkDate . " +1 days");
$chkDate = date("Y-m-d", $timestamp);
} else {
return $chkDate;
}
} while (true);
}
I'm using php and mysqli for my project.
My question is about calculating next available shipping dates.
On my checkout page, my website displays the next available shipping date according to the following rules:
I can ship monday - saturday before 4pm.
I have a table "cantship" containing dates in the format d/m/Y that I cannot ship on because im at work.
So, the next available shipping date displayed should be a monday-saturday unless its past 4pm or todays date matches a date in the cantship table.
So, what I need shown:
If the time now is before 4pm and today is a monday-saturday, I can ship today so show todays date (as long as todays date is not in the cantship table)
If the time now is after 4pm, I cannot ship today so the next shipping date should be a mon-sat thats not in the cantship table.
If the calculated shipping date is in the cantship table, I cant ship on that day, so the next shipping date would have to be the next day thats between mon-sat, thats not in the cantship table.
Here is my code so far: Sorry its messy.
<?php
function nextshipdate ($db)
{
// ========================================================================
// find next available date for despatch
// ========================================================================
$i = 0;
$cutoff = strtotime('today 16:00');
$today1 = strtotime('today');
if ($cutoff >strtotime($today1 ))
{
echo "<p>its after 4pm!<p>";
$i = 1;
}
$tmpDate =date('d-m-Y H:i:s');
$nextBusinessDay = date('d-m-Y ', strtotime($tmpDate . ' +' . $i . ' Weekday'));
$nextavail= date('d-m-Y H:i:s', strtotime($tmpDate . ' +' . $i . ' Weekday'));
$dontuse = array();
$getbiz = $db->get_results("SELECT * from cantship ");
$nowcheck = new DateTime();
// =======================================================
// remove past dates from cantship table
// =======================================================
foreach ($getbiz as $inpast)
{
if (strtotime($inpast->csdate)<= time())
{
//echo $inpast->csdate." has passed!<p>";
$removeold = $db->query("DELETE from cantship where csdate='". $inpast->csdate."'" );
}
}
// =======================================================
// create array of unavailable shipping dates
// =======================================================
if ($getbiz)
{
foreach ($getbiz as $na)
{
$dontuse[]=$na->csdate;
}
}
while (in_array($nextBusinessDay, $dontuse))
{
$i++;
$nextBusinessDay = date('d-m-Y', strtotime($tmpDate . ' +' . $i . ' Weekday'));
}
if(!empty($dontuse))
{
$nbd=$nextBusinessDay;
}
else
{
$nbd=' please contact us.';
}
return $nbd;
}
// ==========================================================================================
Beginning from a Date with the current time you must modify the dateto the next day if
The time is >= 4 pm or
The day is a Sunday or
The day is in the nonshipping list
The nonshiiping list is given as array:
$noShipDates = [
'2020-10-28',
'2020-12-24'
];
The logic can be implemented as a small function.
function nextShipDate(array $noShipDates, $curTime = "now"){
$date = date_create($curTime);
$max = 1000; //protection endless loop
while($max--){
if($date->format('H') >= 16
OR $date->format('w') == 0
OR in_array($date->format('Y-m-d'),$noShipDates)
) {
$date->modify('next Day 00:00');
}
else {
return $date->format('Y-m-d');
}
}
return false;
}
The function returns a string of the form 'yyyy-mm-dd' or false for an error. For test purposes, a date can be specified with the 2nd parameter.
echo nextShipDate($noShipDates, '2020-10-27 16:01');
//2020-10-29
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
I have got a script that repeats activitities.
When the repeat settings are:
repeat "the 2nd tuesday every 2 months, stop at 5 instances" (like google calendar would do).
I can accomplish "the 2nd tuesday every 2 months" with the script below:
<?php
$pubDay = 19;
$pubMonth = 7;
$pubYear = 2017;
$repeatMonths = 2;
$newMonth = $pubMonth;
$newYear = $pubYear;
$raisedMonth = $pubMonth + $repeatMonths;
if ( $raisedMonth > 12 ) {
$newMonth = ($raisedMonth) % 12; // off 12 at starts at 1
$newYear = $pubYear + 1;
} else {
$newMonth = $raisedMonth;
}
$occurenceInMonth = ceil($pubDay / 7); // determine the weekday occurence in the month (b.e. the "2nd thursday")
$dates = array();
foreach (getWeekDayDates($pubDow, $newYear, $newMonth) as $weekdaydate) {
$dates[] = $weekdaydate->format("Y-m-d");
}
// we need the x occurence (-1)
$newPubDate = isset($dates[$occurenceInMonth -1]) ? $dates[$occurenceInMonth -1] . " " . $pubHour . ":" . $pubMin : "";
echo $newPubDate;
function getWeekDayDates($weekday, $y, $m) {
return new DatePeriod(
new DateTime("first " . $weekday . " of $y-$m"),
DateInterval::createFromDateString('next ' . $weekday),
new DateTime("next month $y-$m-01")
);
}
?>
This works like a charm.
But now i need to check wether it is the 5th instance, starting at 17-9-2016.
My script is now like this:
// get the end date
$startdate = "2016-09-17";
$repeatMonths = 2;
$endTime = strtotime($startdate . " +" . ($repeatMonths * $reps) . " months");
if ( $endTime >= strtotime($newPubDate) ) {
$doRepeat = true;
}
But this can go wrong!
By example when the repetitons starts (startddate) at saturday 4-7 and it repeats every first sunday.
When the sunday in the last repetition is on the 6th of the month. The script above returns false, but it shouldnt't.
How can i check on a simple way if it is the 5th occurence?
I would create an array which holds DateTime objects of the next 5 "2nd tuesdays of the month":
$startdate = new \DateTime('second tue of february 2017');
$dates = array();
$repetitions = 5;
for ($i=0; $i<$repetitions; $i++) {
$dates[] = clone $date->modify('+1 month');
}
Using this array it should be easy to check, whether the date is reached or not yet.
I have a table called schedule and a column called Date where the column type is date. In that column I have a range of dates, which is currently from 2012-11-01 to 2012-11-30. I have a small form where the user can enter a range of dates (input names from and to) and I want to be able to compare the range of dates with the dates currently in the database.
This is what I have:
////////////////////////////////////////////////////////
//////First set the date range that we want to use//////
////////////////////////////////////////////////////////
if(isset($_POST['from']) && ($_POST['from'] != NULL))
{
$startDate = $_POST['from'];
}
else
{
//Default date is Today
$startDate = date("Y-m-d");
}
if(isset($_POST['to']) && ($_POST['to'] != NULL))
{
$endDate = $_POST['to'];
}
else
{
//Default day is one month from today
$endDate = date("Y-m-d", strtotime("+1 month"));
}
//////////////////////////////////////////////////////////////////////////////////////
//////Next calculate the total amount of days selected above to use as a limiter//////
//////////////////////////////////////////////////////////////////////////////////////
$dayStart = strtotime($startDate);
$dayEnd = strtotime($endDate);
$total_days = abs($dayEnd - $dayStart) / 86400 +1;
echo "Start Date: " . $startDate . "<br>End Date: " . $endDate . "<br>";
echo "Day Start: " . $dayStart . "<br>Day End: " . $dayEnd . "<br>";
echo "Total Days: " . $total_days . "<br>";
////////////////////////////////////////////////////////////////////////////////////
//////Then we're going to see if the dates selected are in the schedule table//////
////////////////////////////////////////////////////////////////////////////////////
//Select all of the dates currently in the schedule table between the range selected.
$sql = ("SELECT Date FROM schedule WHERE Date BETWEEN '$startDate' AND '$endDate' LIMIT $total_days");
//Run a check on the query to make sure it worked. If it failed then print the error.
if(!$result_date_query = $mysqli->query($sql))
{
die('There was an error getting the dates from the schedule table [' . $mysqli->error . ']');
}
//Set the dates to an array for future use.
// $current_dates = $result_date_query->fetch_assoc();
//Loop through the results while a result is being returned.
while($row = $result_date_query->fetch_assoc())
{
echo "Row: " . $row['Date'] . "<br>";
echo "Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Set this loop to add 1 day to the Start Date until it reaches the End Date
for($i = $dayStart; $i <= $dayEnd; $i = strtotime('+1 day', $i))
{
$date = date('Y-m-d',$i);
echo "Loop Start day: " . date('Y-m-d', $dayStart) . "<br>";
//Run a check to see if any of the dates selected are in the schedule table.
if($row['Date'] != $date)
{
echo "Current Date: " . $row['Date'] . "<br>";
echo "Date: " . $date . "<br>";
echo "It appears as though you've selected some dates that are not in the schedule database.<br>Please correct the issue and try again.";
return;
}
}
}
//Free the result so something else can use it.
$result_date_query->free();
As you can see I've added in some echo statements so I can see what is being produced. From what I can see it looks like my $row['Date'] is not incrementing and staying at the same date. I originally had it set to a variable (currently commented out) but I thought that could be causing problems.
I have created the table with dates ranging from 2012-11-01 to 2012-11-15 for testing and entered all of this php code onto phpfiddle.org but I can't get the username provided to connect.
Here is the link: PHP Fiddle
I'll be reading through the documentation to try and figure out the user connection problem in the meantime, I would really appreciate any direction or advice you can give me.