I have a PHP script which records things based on the day. So it will have a weekly set of inputs you would enter.
I get the data correctly, but when i do $day ++; it will increment the day, going passed the end of the month without ticking the month.
example:
//12/29
//12/30
//12/31
//12/32
//12/33
Where it should look like
//12/29
//12/30
//12/31
//01/01
//01/02
My script is as follows:
$week = date ("Y-m-d", strtotime("last sunday"));
$day = $week;
$run = array(7); //this is actually defined in the data posted to the script, which is pretty much just getting the value of the array index for the query string.
foreach( $run as $key=>$value)
{
$num = $key + 1;
$items[] = "($num, $user, $value, 'run', '$day')";
echo "".$day;
$day ++;
}
Should I be manipulating the datetime differently for day incrementations?
You can use
$day = date("Y-m-d", strtotime($day . " +1 day"));
instead of
$day++;
See live demo in ideone
You refer to $day as a "datetime" but it is just a string - that is what date() returns. So when you do $day++ you are adding 1 to "2015-12-02". PHP will do everything it can to make "2015-12-02" into a number and then add 1 to it, which is not date math. Here is a simple example:
<?php
$name = "Fallenreaper1";
$name++;
echo $name
?>
This will output:
Fallenreaper2
This is how I would do it, using an appropriate data type (DateTime):
<?php
$day = new DateTime('last sunday');
$run = array(7);
foreach ($run as $key => $value) {
$num = $key + 1;
$dayStr = $day->format('Y-m-d');
$items[] = "($num, $user, $value, 'run', '$dayStr')";
echo $dayStr;
$day->modify('+1 day');
}
To increase time you should use strtotime("+1 day");
here is simple example of using it
<?php
$now_time = time();
for($i=1;$i<8;$i++) {
$now_time = strtotime("+1 day", $now_time);
echo date("Y-m-d", $now_time) . "<br>";
}
?>
Related
I have a php code as shown below in which on the 1st day of every month, I am copying 2nd JSON object array (next_month) content into 1st JSON object array (current_month).
In the 2nd JSON object array (next_month), I want to have next month dates. That will also happen on the 1st day of every month. Currently I am storing nada. Let us suppose that today is 1st day of November.
php code:
$value = json_decode(file_get_contents('../hyt/dates.json'));
if ((date('j') == 1)) {
$month = 11;
$year = date('Y');
$current_month_days = (date('t', strtotime($year . '-' . $month . '-01')));
$next_month_days = (date('t', strtotime($year . '-' . ($month + 1) . '-01')));
$value->current_month = $value->next_month; // Line Y
$value->next_month = array_fill(0, ($next_month_days), nada); // Line Z
}
The current look of JSON (dates.json) is shown below:
{"current_month": ["2020-10-01", "2020-10-02", "2020-10-03", "2020-10-04", "2020-10-05", "2020-10-06", "2020-10-07", "2020-10-08", "2020-10-09", "2020-10-10", "2020-10-10", "2020-10-12", "2020-10-13", "2020-10-14", "2020-10-15", "2020-10-16", "2020-10-17", "2020-10-18", "2020-10-19", "2020-10-20", "2020-10-21", "2020-10-22", "2020-10-23", "2020-10-24", "2020-10-25", "2020-10-26", "2020-10-27", "2020-10-28", "2020-10-29", "2020-10-30","2020-10-31"],
"next_month": ["2020-11-01", "2020-11-02", "2020-11-03", "2020-11-04", "2020-11-05", "2020-11-06", "2020-11-07", "2020-11-08", "2020-11-09", "2020-11-11", "2020-11-11", "2020-11-12", "2020-11-13", "2020-11-14", "2020-11-15", "2020-11-16", "2020-11-17", "2020-11-18", "2020-11-19", "2020-11-20", "2020-11-21", "2020-11-22", "2020-11-23", "2020-11-24", "2020-11-25", "2020-11-26", "2020-11-27", "2020-11-28", "2020-11-29", "2020-11-30"] }
Problem Statement:
I am wondering what changes I should make at Line Z so that in the second JSON object array, I am able to get next month dates. At present, I am storing nada.
The content which I want in the JSON on the 1st day of November month after successful execution of Line Y and Line Z is:
{"current_month": ["2020-11-01", "2020-11-02", "2020-11-03", "2020-11-04", "2020-11-05", "2020-11-06", "2020-11-07", "2020-11-08", "2020-11-09", "2020-11-11", "2020-11-11", "2020-11-12", "2020-11-13", "2020-11-14", "2020-11-15", "2020-11-16", "2020-11-17", "2020-11-18", "2020-11-19", "2020-11-20", "2020-11-21", "2020-11-22", "2020-11-23", "2020-11-24", "2020-11-25", "2020-11-26", "2020-11-27", "2020-11-28", "2020-11-29", "2020-11-30"],
"next_month": ["2020-12-01", "2020-12-02", "2020-12-03", "2020-12-04", "2020-12-05", "2020-12-06", "2020-12-07", "2020-12-08", "2020-12-09", "2020-12-11", "2020-12-11", "2020-12-12", "2020-12-13", "2020-12-14", "2020-12-15", "2020-12-16", "2020-12-17", "2020-12-18", "2020-12-19", "2020-12-20", "2020-12-21", "2020-12-22", "2020-12-23", "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27", "2020-12-28", "2020-12-29", "2020-12-30", "2020-12-31"] }
This is what I have tried:
This is what I have tried at Line Z but its storing only today's date in JSON object array.
$value->next_month = array_fill(0, ($next_month_days), date("Y-m-d")); // Line Z
I think you should completely recreate your JSON string. It starts on the first day of the current month. The loop always runs as long as the month remains. The whole thing then again for the following month.
$arr = $cur = [];
$date = date_create('first day of this month 00:00');
$startMonth = $month = $date->format('m');
while($startMonth == $month){
$cur[] = $date->format('Y-m-d');
$date->modify('+1 Day');
$month = $date->format('m');
}
$arr["current_month"] = $cur;
$startMonth = $month;
$cur = [];
while($startMonth == $month){
$cur[] = $date->format('Y-m-d');
$date->modify('+1 Day');
$month = $date->format('m');
}
$arr["next_month"] = $cur;
$jsonStr = json_encode($arr);
You are using array_fill, which is used to fill at least part of an array with the same value. I would recommend using a simple for loop:
$next_month_array = [];
$next_month = $month < 12 ? $month + 1 : 1;
$year = date('Y');
for($day_counter = 1; $day_counter <= $next_month_days; $day_counter++) {
$next_month_array[] = "$year-$next_month-$day_counter";
}
$value->next_month = $next_month_array;
I am trying to show results of each month.
Im having this for loop:
foreach ($overview as $day) {
$year = date("Y") - 1;
if ($day->user == $info->id) {
$startDate = new DateTime($day->Calendar_startdate);
$endDate = new DateTime($day->Calendar_enddate);
$s = $startDate->format('Y-m-d');
$e = $endDate->format('Y-m-d');
if ($s > $year) {
$workdays = number_of_working_days($s, $e);
$daysleft = $daysleft + $workdays;
} else {
}
}
}
This for loop is also in an if statement which echos the months.
Now I need to let it work for the months January, February etc...
I am able to not show results if in the previous year which works well.
If you want to compare $s with $year just change $year to :
$time = new DateTime('now');
/*** you can use `now` for today
/* or you can change to a fixed date exmp: 2016-01-01
*/
$year = $time->modify('-1 year')->format('Y-m-d');
Than you can compare $s > $year
I fixed by checking each month if it contained for example -01-
DB::table('Calendar')->where('Calendar_startdate', 'like','%' . $monthnumber . '%')->where('user', $info->id)->where('Calendar_type',2)->get();
Hi firstly heres my code.
<?php
function getDatesBetween2Dates($startTime, $endTime) {
$day = 86400;
$format = 'd-m-Y';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
$numDays = round(($endTime - $startTime) / $day) + 1;
$days = array();
for ($i = 0; $i < $numDays; $i++) {
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
///
$days = getDatesBetween2Dates(date('d-m-Y', strtotime('-3 weeks Monday')),date('d-m-Y', strtotime('+2 weeks Sunday')));
foreach($days as $key => $value){
$dayNumber = date('d', strtotime($value));
//echo $value;
echo "<div id=\"day\">
<div id=\"number\">$dayNumber</div>";
////////////sql seearch//\\\/////////
//Connect to db
include("../djwbt.php");
$sql = "SELECT * FROM daysummary WHERE date='$value'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$place = $row['place'];
$invoicedate = $row['date'];
}
/////////////end sql search//////////
echo "<div id=\"event\">$place</div>
</div><!-- end day -->";
}
?>
What i am trying to do is show all dates between two points and for each of the dates search my db using the date as a where clause. i have tried putting the search in a few places but im not getting the right results.
this gives me the same result in each date.
e.g. 17th = (empty) as in my db, 18TH = HOME (as in my db), 19th = HOME (not as in my db), 20th = HOME (this continues all the way through fore each)
the link in each fore each works perfectly?
Any help would be amazing.
I would make one statement that gets all the needed data from your database:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
then use the foreach loop for the results
Note that mysql_ functions are deprecated, Try switching to mysqli_ or PDO
Here I access 'date' key values from rows of DB table. And I can echo these values, no problem.
$res = $mysqli->query("SELECT * FROM alfred ORDER BY id ASC");
$row = $res->fetch_all(MYSQLI_ASSOC);
foreach ($row as $key => $value){
$availDate = $value['date'];
echo $availDate.'<br />';
}
This loop above shows all 'date' values from DB, in this case there are 3 dates- "2012-09-25" "2012-09-27" and "2012-09-29".
But then I need to compare each of these 'date' values against values of $date->format('Y-m-d') from the code below and display each date with corresponding "busy" or "available" status into separate <td> of the table. My following version compares only the "last" value of 'date' key - "2012-09-29", but I need to compare each 'date' value from the array above, it means also "2012-09-25" and "2012-09-27". I have tried many versions but still unsuccessful. Any ideas?
$date = new DateTime();
$endDate = new DateTime('+10 day');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
if ($date->format('Y-m-d') == $availDate){
echo '<td>'.$date->format('Y-m-d/D').' busy</td>';
} else {
echo '<td>'.$date->format('Y-m-d/D').' available</td>';
}
}
Here is the result I am getting now:
2012-09-21/Fri available 2012-09-22/Sat available 2012-09-23/Sun available 2012-09-24/Mon available 2012-09-25/Tue available 2012-09-26/Wed available 2012-09-27/Thu available 2012-09-28/Fri available 2012-09-29/Sat busy 2012-09-30/Sun available
But in fact I need to show "busy" status also into <td> of "2012-09-25" and <td> of "2012-09-27" as these also are 'date' values that are existing in $row array. Unfortunately I can not post any images here to show, but I hope my result above gives you the idea.
SOLVED with the help of in_array below:
$aAvailDate = array();
foreach ($row as $key => $value){
$aAvailDate[] = $value['date'];
}
$date = new DateTime();
$endDate = new DateTime('+10 day');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
if (in_array($date->format('Y-m-d'), $aAvailDate)){
echo '<td>'.$date->format('Y-m-d/D').' busy</td>';
} else {
echo '<td>'.$date->format('Y-m-d/D').' available</td>';
}
}
I haven't tested your code, but I think you are running ->format('Y-m-d') unnecessarily here, and this is messing up your logic.
Every time you run that, PHP is turning your object into a string, which you are then comparing against other strings. This won't do anything useful.
Instead, you should be using the features of the DateTime class to compare the objects themselves. The only time you should need to use the format() method is when outputting to the browser, into an SQL query, etc
Although your Question is Unclear but AFAIK
you want to display "Busy" if available date occurs between given date upto 3 Weeks
otherwise display "free"
I would like to suggest you to do this with MySQL (Not tested)
SELECT *,
IF( `DateCol` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 3 WEEK), 'Busy','Free')
AS status
FROM TableName
Try a while loop instead of a foreach. Also, compare the DateTime objects directly, not the formatted strings.
$date = new DateTime();
$endDate = new DateTime('+3 week');
while( $date < $endDate) {
if ($date->format('Y-m-d') == $availDate){
echo '<td class="busy">busy</td>';
} else {
echo '<td>free</td>';
}
$date->modify("+1 day");
}
Something like this? (If I understand what you're trying to do correctly)
<?php
$avail_dates = array();
$res = $mysqli->query("SELECT DATE_FORMAT(date, '%Y-%m-%d') AS availDate FROM alfred ORDER BY id ASC");
$row = $res->fetch_all(MYSQLI_ASSOC);
foreach ($row as $key => $value){
$avail_dates[] = $value['availDate'];
}
$startDate = date('Y-m-d');
$endDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime($startDate)) . " +3 week"));
?>
<table>
<?php
foreach ($avail_dates as $availDate){
echo "<tr><td>$availDate</td>";
if (($startDate <= $availDate) && ($endDate >= $availDate)){
echo "<td class='busy'>busy</td>";
}else{
echo "<td>free</td>";
}
echo "</tr>";
}
?>
Instead of printing values, I would add them to the array, and then run a loop on that array, comparing the values to the given start and end dates. I also wouldn't fetch all from the table if you nly need a date.
May be like this?
$date = new DateTime();
$endDate = new DateTime('+3 week');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
$tempDate = $date->format('Y-m-d');
if ($tempDate === $availDate){
echo '<td class="busy">busy</td>';
} else {
echo '<td>free</td>';
}
}
Does anyone have a PHP snippet to calculate the next business day for a given date?
How does, for example, YYYY-MM-DD need to be converted to find out the next business day?
Example:
For 03.04.2011 (DD-MM-YYYY) the next business day is 04.04.2011.
For 08.04.2011 the next business day is 11.04.2011.
This is the variable containing the date I need to know the next business day for
$cubeTime['time'];
Variable contains: 2011-04-01
result of the snippet should be: 2011-04-04
Next Weekday
This finds the next weekday from a specific date (not including Saturday or Sunday):
echo date('Y-m-d', strtotime('2011-04-05 +1 Weekday'));
You could also do it with a date variable of course:
$myDate = '2011-04-05';
echo date('Y-m-d', strtotime($myDate . ' +1 Weekday'));
UPDATE: Or, if you have access to PHP's DateTime class (very likely):
$date = new DateTime('2018-01-27');
$date->modify('+7 weekday');
echo $date->format('Y-m-d');
Want to Skip Holidays?:
Although the original poster mentioned "I don't need to consider holidays", if you DO happen to want to ignore holidays, just remember - "Holidays" is just an array of whatever dates you don't want to include and differs by country, region, company, person...etc.
Simply put the above code into a function that excludes/loops past the dates you don't want included. Something like this:
$tmpDate = '2015-06-22';
$holidays = ['2015-07-04', '2015-10-31', '2015-12-25'];
$i = 1;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
while (in_array($nextBusinessDay, $holidays)) {
$i++;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
}
I'm sure the above code can be simplified or shortened if you want. I tried to write it in an easy-to-understand way.
For UK holidays you can use
https://www.gov.uk/bank-holidays#england-and-wales
The ICS format data is easy to parse. My suggestion is...
# $date must be in YYYY-MM-DD format
# You can pass in either an array of holidays in YYYYMMDD format
# OR a URL for a .ics file containing holidays
# this defaults to the UK government holiday data for England and Wales
function addBusinessDays($date,$numDays=1,$holidays='') {
if ($holidays==='') $holidays = 'https://www.gov.uk/bank-holidays/england-and-wales.ics';
if (!is_array($holidays)) {
$ch = curl_init($holidays);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$ics = curl_exec($ch);
curl_close($ch);
$ics = explode("\n",$ics);
$ics = preg_grep('/^DTSTART;/',$ics);
$holidays = preg_replace('/^DTSTART;VALUE=DATE:(\\d{4})(\\d{2})(\\d{2}).*/s','$1-$2-$3',$ics);
}
$addDay = 0;
while ($numDays--) {
while (true) {
$addDay++;
$newDate = date('Y-m-d', strtotime("$date +$addDay Days"));
$newDayOfWeek = date('w', strtotime($newDate));
if ( $newDayOfWeek>0 && $newDayOfWeek<6 && !in_array($newDate,$holidays)) break;
}
}
return $newDate;
}
function next_business_day($date) {
$add_day = 0;
do {
$add_day++;
$new_date = date('Y-m-d', strtotime("$date +$add_day Days"));
$new_day_of_week = date('w', strtotime($new_date));
} while($new_day_of_week == 6 || $new_day_of_week == 0);
return $new_date;
}
This function should ignore weekends (6 = Saturday and 0 = Sunday).
This function will calculate the business day in the future or past. Arguments are number of days, forward (1) or backwards(0), and a date. If no date is supplied todays date will be used:
// returned $date Y/m/d
function work_days_from_date($days, $forward, $date=NULL)
{
if(!$date)
{
$date = date('Y-m-d'); // if no date given, use todays date
}
while ($days != 0)
{
$forward == 1 ? $day = strtotime($date.' +1 day') : $day = strtotime($date.' -1 day');
$date = date('Y-m-d',$day);
if( date('N', strtotime($date)) <= 5) // if it's a weekday
{
$days--;
}
}
return $date;
}
What you need to do is:
Convert the provided date into a timestamp.
Use this along with the or w or N formatters for PHP's date command to tell you what day of the week it is.
If it isn't a "business day", you can then increment the timestamp by a day (86400 seconds) and check again until you hit a business day.
N.B.: For this is really work, you'd also need to exclude any bank or public holidays, etc.
I stumbled apon this thread when I was working on a Danish website where I needed to code a "Next day delivery" PHP script.
Here is what I came up with (This will display the name of the next working day in Danish, and the next working + 1 if current time is more than a given limit)
$day["Mon"] = "Mandag";
$day["Tue"] = "Tirsdag";
$day["Wed"] = "Onsdag";
$day["Thu"] = "Torsdag";
$day["Fri"] = "Fredag";
$day["Sat"] = "Lørdag";
$day["Sun"] = "Søndag";
date_default_timezone_set('Europe/Copenhagen');
$date = date('l');
$checkTime = '1400';
$date2 = date(strtotime($date.' +1 Weekday'));
if( date( 'Hi' ) >= $checkTime) {
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Saturday'){
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Sunday') {
$date2 = date(strtotime($date.' +2 Weekday'));
}
echo '<p>Næste levering: <span>'.$day[date("D", $date2)].'</span></p>';
As you can see in the sample code $checkTime is where I set the time limit which determines if the next day delivery will be +1 working day or +2 working days.
'1400' = 14:00 hours
I know that the if statements can be made more compressed, but I show my code for people to easily understand the way it works.
I hope someone out there can use this little snippet.
Here is the best way to get business days (Mon-Fri) in PHP.
function days()
{
$week=array();
$weekday=["Monday","Tuesday","Wednesday","Thursday","Friday"];
foreach ($weekday as $key => $value)
{
$sort=$value." this week";
$day=date('D', strtotime($sort));
$date=date('d', strtotime($sort));
$year=date('Y-m-d', strtotime($sort));
$weeks['day']= $day;
$weeks['date']= $date;
$weeks['year']= $year;
$week[]=$weeks;
}
return $week;
}
Hope this will help you guys.
Thanks,.
See the example below:
$startDate = new DateTime( '2013-04-01' ); //intialize start date
$endDate = new DateTime( '2013-04-30' ); //initialize end date
$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday
$interval = new DateInterval('P1D'); // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
For more info: http://goo.gl/YOsfPX
You could do something like this.
/**
* #param string $date
* #param DateTimeZone|null|null $DateTimeZone
* #return \NavigableDate\NavigableDateInterface
*/
function getNextBusinessDay(string $date, ? DateTimeZone $DateTimeZone = null):\NavigableDate\NavigableDateInterface
{
$Date = \NavigableDate\NavigableDateFacade::create($date, $DateTimeZone);
$NextDay = $Date->nextDay();
while(true)
{
$nextDayIndexInTheWeek = (int) $NextDay->format('N');
// check if the day is between Monday and Friday. In DateTime class php, Monday is 1 and Friday is 5
if ($nextDayIndexInTheWeek >= 1 && $nextDayIndexInTheWeek <= 5)
{
break;
}
$NextDay = $NextDay->nextDay();
}
return $NextDay;
}
$date = '2017-02-24';
$NextBussinessDay = getNextBusinessDay($date);
var_dump($NextBussinessDay->format('Y-m-d'));
Output:
string(10) "2017-02-27"
\NavigableDate\NavigableDateFacade::create($date, $DateTimeZone), is provided by php library available at https://packagist.org/packages/ishworkh/navigable-date. You need to first include this library in your project with composer or direct download.
I used below methods in PHP, strtotime() does not work specially in leap year February month.
public static function nextWorkingDay($date, $addDays = 1)
{
if (strlen(trim($date)) <= 10) {
$date = trim($date)." 09:00:00";
}
$date = new DateTime($date);
//Add days
$date->add(new DateInterval('P'.$addDays.'D'));
while ($date->format('N') >= 5)
{
$date->add(new DateInterval('P1D'));
}
return $date->format('Y-m-d H:i:s');
}
This solution for 5 working days (you can change if you required for 6 or 4 days working). if you want to exclude more days like holidays then just check another condition in while loop.
//
while ($date->format('N') >= 5 && !in_array($date->format('Y-m-d'), self::holidayArray()))