I want to add particular days to current date. where days are taking from database field. It adds to the present date properly but at next day, date is going to update to the present date again.so how to keep date unchanged. It should take only once in PHP
$day= $cur["Days"];
if(($cur["Days"]) == 0){
$new = '';
} else {
$Date = date('20y-m-d');
$new = date("20y-m-d", strtotime($Date . ' + ' . $day . ' days'));
}
input if $day=1,$day+$new
output= jan19,this is the output of one row and my problem is it should remain as it is for this row but now for next day it is going to change to jan20 that should not happen
Related
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
PHP 7.1.7
There's a work function I'm dealing with that has a custom "week" (where a "week" for this function is Saturday through Friday).
For any given day of the week, how could I set two variables to contain the start of the custom defined week (Saturday) and the end of the custom defined week (Friday).
So, if I had a date of 8-11-17, I would need to come up with a a start date variable holding 8-05-17 and an end date variable holding 8-11-17.
Thanks
Not sure if I understood the question correct but is this what you are looking for?
It uses strtotime() to find previous saturday from input. Then next friday from that saturday.
$Input = "08/12/2017";
if(date("l", strtotime($Input)) == "Saturday"){
$Saturday = strtotime($Input);
}else{
$Saturday = strtotime($Input . " previous saturday");
}
$Friday = strtotime(date("m/d/Y", $Saturday) . " next friday");
echo date("m/d/Y", $Saturday) . " to " . date("m/d/Y", $Friday);
https://3v4l.org/l4g8D
EDIT; I just noticed if the Input is a saturday my code choosed the wrong dates. Corrected.
you could use date('w') to determine the day of week for given date.
If the number found is less than 6, move that number + 1 backwards. That's your starting date. End date will be 7 days later:
<?php
$date = new DateTime('08-11-2017');
$daynumber = $date->format('w');
if($daynumber < 6) {
$tomove = $daynumber + 1;
$date->modify('-' . $tomove.'day');
}
$startdate = $date;
$enddate = clone $date;
$enddate->modify('+7day');
echo $startdate->format('d-m-y');
echo $enddate->format('d-m-y');
?>
edit
forgot the word "day" in modify
I have date in this form - - 20160428000000 (28th April 2016) i.e yyyymmdd...
I need that if some days(eg. 3) are added to this date - it should add them but not exceed the month(04) - expected output - 20160430000000 - 30th April
Similarly, 20160226000000 + 5days should return 20160229000000 i.e leap year Feb. That means, it should not jump to another month.
Any hints/Ideas ?
Another alternative would be to use DateTime classes to check it out:
First of course create your object thru the input. Then, set the ending day of the month object.
After that, make the addition then check if it exceeds the ending day. If yes, set it to the end, if not, then get the result of the addition:
$day = 5; // days to be added
$date = '20160226000000'; // input date
$dt = DateTime::createFromFormat('YmdHis', $date); // create the input date
$end = clone $dt; // clone / copy the input
$end->modify('last day of this month'); // and set it to last day
$dt->add(DateInterval::createFromDateString("+{$day} days")); // add x days
// make comparision
$final_date = ($dt > $end) ? $end->format('YmdHis') : $dt->format('YmdHis');
echo $final_date;
For this you can try like this:
$given_date = 20160428000000;
$no_of_day = 3;
if(date('m',strtotime($given_date)) < date('m',strtotime($given_date ." +".$no_of_day."days"))){
echo "Exceeded to next month <br/>";
echo "Last date of month should be: ".date("t M Y", strtotime($given_date));
}
else {
echo "Next date will be after ".$no_of_day." day(s)<br/>";
echo date('d M Y',strtotime($given_date ." +".$no_of_day."days"));
}
If month will jump to next month then it will show the current month last date.
other wise it will show date after number of days extended.
If the added date exceeds last day, will select the last day as the new date.
<?php
$date_orig = 20160226000000;
$add_day = 5; # No. of days to add
$added_date = strtotime($date_orig. ' + '.$add_day.' days'); // Add $add_day to $date_orig
$last_date = strtotime(date("YmtHis", strtotime($date_orig))); // Last day of $date_orig
$new_date = ($added_date > $last_date) ? $last_date : $added_date; // check the added date exceeds the last date
$new_date_format = date("YmdHis", $new_date); // Format Date
echo $new_date_format;
?>
<?php
$month_end = date('t-m-Y'); // Gets the last day of the month; e.g 31-07-2019
echo $month_end;
?>
I am trying to add days and/or weeks to a date that is being pulled from a database. All I am getting is the 12-31-1969 default date when it cannot output correctly. Here is my code:
$lastFeed = "6-25-2013"; //pulled from database last feed date
$feedSchedule = "2"; //pulled from database number of weeks.
$nextFeeding = date("m-d-Y", strtotime($lastFeed . ' + ' . $feedSchedule. ' week'));
I have also tried multiplying the days times the $feedSchedule variable and replacing week(s) with day(s).
6-25-2013 is not a valid date format. Try YYYY-MM-DD
Here is code that will work and account for the invalid Date Time String
function nextFeeding($lastFeed,$feedSchedule){
//fix date format
$correctedDate = explode("-",$lastFeed);
//pad month to two digits may need to do this with day also
if($correctedDate[0] < 10 && strlen($correctedDate[0])!==2){
$correctedDate[0] = "0".$correctedDate[0];
}
$correctedDate = $correctedDate[2]."-".$correctedDate[0]."-".$correctedDate[1];
//get the next feeding date
$nextFeeding = date("m-d-Y", strtotime($correctedDate . ' + ' . $feedSchedule. ' week'));
//return value
return $nextFeeding;
}
$lastFeed = "6-25-2013"; //pulled from database last feed date
$feedSchedule = "2"; //pulled from database number of weeks.
$nextFeeding = nextFeeding($lastFeed,$feedSchedule);
echo $nextFeeding;
returns
07-09-2013