Add days to date variable - php

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

Related

Adding days to current date only once

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

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

php parse csv file based on date range

I am trying to display lines from a file based on a date range (ex: get today + next 7 days based on date field). I'm not familiar with PHP.
I have the following to read the file and create an array from the contents:
$txt_file = file_get_contents('shipping_dates.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
$info[$row]['Order_Date'] = $row_data[0];
$info[$row]['Free_Shipping'] = $row_data[1];
$info[$row]['Rush_Order'] = $row_data[2];
//display data
echo 'Row ' . $row . ' Order_Date: ' . $info[$row]['Order_Date'] . '<br />';
echo 'Row ' . $row . ' Free_Shipping: ' . $info[$row]['Free_Shipping'] . '<br />';
echo 'Row ' . $row . ' Rush_Order: ' . $info[$row]['Rush_Order'] . '<br />';
}
This works great - Now I need to grab the individual lines based on a date range and display only the lines within the range only, not the entire contents for each of these 3 options.
I would do:
Assuming your desired date range is only for 'entire days' without considering the hours.
Get the date range in unix TimeStamp format. Example for January 2018. You have to manually add " 00:00:00" and " 23:59:59" so you cover the full days.
Before your foreach loop:
$filter_date_from = '2018-01-01';
$filter_date_to = '2018-01-31';
$date_from = $filter_date_from.' 00:00:00'; // add begin of the day
$date_to = $filter_date_to.' 23:59:59'; // add end of the day
$date_from_ts = strtotime($date_from); // convert to unix timestamp
$date_to_ts = strtotime($date_to);
Then inside the loop you would check this, once you have $info[$row]['Order_Date'] stuffed:
// convert the order date to unix timestamp
$order_date_ts = strtotime($info[$row]['Order_Date']);
// just compare
if ($order_date_ts >= $date_from_ts && $order_date_ts <= $date_to_ts) {
// you want the CSV line because it is IN the date range
}
With this solution you don't care if the Order_Date includes hours, minutes and/or seconds, or none of them (strtotime will assume 00:00:00 if none are provided).
Please note that the dates/datetimes must be in a format that the php function "strtotime" understands, like Y-m-d. See documentation for strtotime if you get weird results.
Not tested but let me know if it works for you...

Calculating number of hours from multiple dateTimes php

I am retrieving records from a database which have separate date and time field and combining them into date time objects so that I can get the difference between start and finish date/time. I also want to calculate to total number of hours that have passed for the number of records returned.
My current code is like this
$temp_total = date_create("00:00");
while($row = mysqli_fetch_assoc($result))
{
$startDate = $row['StartDate'];
$startTime = $row['StartTime'];
$start = $startDate . " " . $startTime;
$start = new DateTime($start);
$finishDate = $row['FinishDate'];
$finishTime = $row['FinishTime'];
$finish = $finishDate . " " . $finishTime;
$finish = new DateTime($finish);
$duration = $start->diff($finish);
$temp_total->add($duration);
}
This just ends up with the times wrapping around i.e. 8hr, 12hr and 12 hrs gives me a total of 8 hours which I assume is because I am missing the added day somewhere.
Am I going about this in the right way or is there a better way of doing it?

Start Date and Start Time Less than End Date and End Time Validation

Start Time, End Date and End Time variables.
The Date Variables are formatted yyyy-mm-dd
The Time Variables are formatted hh-mm (however only on hour numbers are usable, e.g Minutes is always 00)
I can insert these variables into my database no problem, however before I do I want to check that the start date and time is before the end date and time. I know how to check if the time is earlier, and the date is earlier, but I cannot check the time and date together and I would appreciate any help?
$_POST['start_time']
$_POST['end_time']
$_POST['start_date']
$_POST['end_date']
are the variables and how I am grabbing them.
Use DateTime objects to make life simple for yourself:
<?php
// assuming the following values...
$_POST['start_time'] = '06:00';
$_POST['end_time'] = '10:00';
$_POST['start_date'] = '2012-01-01';
$_POST['end_date'] = '2013-06-02';
//set up two DateTime objects
$start = DateTime::createFromFormat('Y-m-d H-i', $_POST['start_date'] . ' ' . $_POST['start_time']);
$end = DateTime::createFromFormat('Y-m-d H-i', $_POST['end_date'] . ' ' . $_POST['end_time']);
// check if they're valid
if ($start < $end) {
echo 'We are good...';
} else {
echo 'Something bad happened...';
}
Bear in mind that this assumes that your $_POSTed values are valid. If you haven't sanitized them already, wrap it in a try/catch at least.
function getTime ($ymd, $hi) {
return strtotime($ymd." ".$hi);
}
if (getTime($_POST['start_date'], $_POST['start_time']) < getTime($_POST['end_date'], $_POST['end_time'])) {
echo "Ok!";
}
Simply convert it to an Unix-timestamp and then compare.
I would use DateTime::createFromFormat() for it. Like this:
$start = DateTime::createFromFormat('Y-m-d H-i',
$_POST['start_date'] . ' ' . $_POST['start_time']);
Try exploding the arrays and then using mktime() function to pass the date to seconds. Then, just compare both dates, the bigger in seconds is the later.
list($strHour, $strMin) = explode('-', $_POST['start_time']);
list($endHour, $endMin) = explode('-', $_POST['end_time']);
list($strYear, $strMonth, $strDay) = explode('-', $_POST['start_date']);
list($endYear, $endMonth, $endDay) = explode('-', $_POST['end_date']);
$startSeconds = mktime($strHour, $strMin, 0, $strMonth, $strDay, $strYear);
$endSeconds = mktime($endHour, $endMin, 0, $endMonth, $endDay, $endYear);
if ($startSeconds > $endSeconds) {
echo 'Start is bigger';
}

Categories