Please see my PHP code
$data= '<select>';
for($y = 1; $y <= 52; $y++) {
$numweek = date("W",strtotime('+ '.$y.' weeks', mktime(0,0,0,1,1,$year,-1))); // display 1 to 52
$namemonth = date("F",strtotime('+ '.$y.' weeks', mktime(0,0,0,1,1,$year,-1))); // display january to december
$data .= '<optgroup label="'.$namemonth.'">\n';
for($x = 1; $x <= 52; $x++) {
$data.= '<option value="'.$x.'"'.($x != $week ? '' : ' selected="selected"').'>Week '.$x.'</option>';
}
$data.= '</optgroup>';
}
$data.= '</select>';
I want to display:
January
Week 1
Week 2
Week 3
Week 4
February
Week 5
Week 6
Week 7
Week 8
.......
December
...
Week 52
Here,I just mention weeknumber for two month. If you want to get for all the month then you can modify $inputArray Array.
$inputArray = ["1(Jan)","2(feb)"];
$weekRange = [];
foreach ($inputArray as $val) {
// parse the input string to extract the month
list(, $month) = sscanf($val, '%d(%[^)]s)');
// Get timestamp for the 1st day of the requested month (using current year)
$startMonth = strtotime('1-' . $month);
// Get the ISO week number for the 1st day of the requested month
$startWeek = date('W', $startMonth);
// Get timestamp for the last day of the requested month (using current year)
$endMonth = strtotime('+1 Month -1 Day', $startMonth);
// Get the ISO week number for the last day of the requested month
$endWeek = date('W', $endMonth);
// get a range of weeks from the start week to the end week
if ($startWeek > $endWeek) {
// start week for january in previous year
$weekRange[$val] = range(1, $endWeek);
array_unshift($weekRange, intval($startWeek));
} else {
$weekRange[$val] = range($startWeek, $endWeek);
}
}
echo "<pre>";
print_r($weekRange);
exit;
OUTPUT
Array
(
[1(Jan)] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
[2(feb)] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
[4] => 9
)
)
Related
I need to add days (input type number + input type date) but the result must be an array so I can INSERT one after another into the Database.
Here's the code (After HTML Form submitted):
<?php
$start_date = '2017-12-22';
$duration = '3';
$d = new DateTime($start_date);
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i <= $duration; $i++){
// add 1 day to timestamp-
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t + $addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay === 6 || $nextDay === 7) {
$i --;
}
// modify timestamp, add 1 day
$t = $t + $addDay;
$d->setTimestamp($t);
$day_off = $d->format( 'Y-m-d' ). "<br />";
echo $day_off;
$query = "INSERT SQL";
}
?>
From echo $day_off result I get:
2017-12-23
2017-12-24
2017-12-25
2017-12-26
Instead of 23, 24, 25, 26. I need to get the result below:
2017-12-22
2017-12-25
2017-12-26
2017-12-27
22 is the input date, start from 25 because 23 and 24 are Sat and Sun and weekends need to be excluded.
How can I achieve this result? I've been searching on the net but unfortunately, I couldn't find what I needed.
#C. Geek answer made it to works, but I have a more complex question here, since my account are not eligible to ask more question so I'll ask here.
So here's what I've tried so far (with #C. Geek answer) :
<?php
// loop for X days
for($i=0; $i < $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$day_off[] = $t;
foreach($day_off as $dayoff) {
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE `date` = '$dayoff' "));
}
$holiday[] = $data_holiday['date'];
$date = array_diff($day_off, $holiday);
$dayoff_ = $holiday;
?>
Start date : 2017-12-29
Duration : 5 days
From print_r($day_off); I'm getting this result :
Array ( [0] => 2017-12-29 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 [2] => 2018-01-02 )
And from print_r($holiday); I'm getting this result :
Array ( [0] => ) Array ( [0] => [1] => 2018-01-01 ) Array ( [0] => [1] => 2018-01-01 [2] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => [4] => )
The national date fetched from database is 2018-01-01 with 5 looping result, the final date result I need to make are 29 Dec, 02 Jan 03 Jan and 04 Jan, 05 Jan.
Any help will be much appreciated.
Thanks.
https://stackoverflow.com/a/4261223/6288442
If you are limiting to weekdays use the string weekdays.
echo date ( 'Y-m-j' , strtotime ( '3 weekdays' ) );
This should jump you ahead by 3 weekdays, so if it is Thursday it will
add the additional weekend time.
Source: http://www.php.net/manual/en/datetime.formats.relative.php
As for formatting:
http://php.net/manual/en/function.strftime.php
string strftime ( string $format [, int $timestamp = time() ] )
If you need more help with writing the code than these, please do tell in a comment
Here is my full answer:
$start_date = '2017-12-22';
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$arr[]=$t;
}
Get the holidays before the looping, then in the loop, check if date is in_array before adding it to $arr.
e.g.
$start_date = '2017-12-22';
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE YEAR(`date`) BETWEEN YEAR('$start_date') AND YEAR('$start_date')+1 "));
$holidays =
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
if(!in_array($t,$data_holiday))
$arr[]=$t;
}
FINALLY!! After several hours I fixed everything. Here's the code how I manage to skip (Sun and Monday) and also Skip the Holiday's fetched from the database (based on #C.Geek answers + several tweaking):
<?php
include 'conn.php';
$start_date = mysqli_real_escape_string($con, $_POST['start_date']);
$duration = mysqli_real_escape_string($con, $_POST['duration']);
// loop for X days
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = explode(", ", strftime("%Y-%m-%d", $d));
foreach ($t as $date) {
$to_encode = array("date" => $date);
$date_where = $to_encode['date'];
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT `date` AS '0' FROM `holiday_master_data` WHERE DATE(`date`) BETWEEN DATE('$date_where') AND DATE('$date_where') + 1 GROUP BY `id` "));
$encode_holiday = array("date" => $data_holiday[0]);
break;
}
$holiday = array_unique($encode_holiday);
$dayoff = array_diff($t, $holiday);
foreach($dayoff as $date) {
$query = mysqli_query($con, "INSERT INTO ");
if ($query) {
echo "<script>alert('Absence Saved'); window.location ='document.php' </script>";
} else {
echo "<script>alert('Gagal'); window.location ='document.php' </script>";
}
}
}
?>
Hope this helps anyone seeking the same problem I had.
Cheers.
This question already has answers here:
Find weekly periods (starting on a Monday) for a month
(3 answers)
Closed 5 years ago.
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.
$month = $_GET['month'];
$year = $_GET['year'];
...
Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017
Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.
Thanks.
Here is one method that loops with strtotime.
I add 86400*7 on Unix to add a week.
$month = 2;
$year = 2017;
$week = date("W", strtotime($year . "-" . $month ."-01")); // weeknumber of first day of month
Echo date("d/m/Y", strtotime($year . "-" . $month ."-01")) ." - "; // first day of month
$unix = strtotime($year."W".$week ."+1 week");
While(date("m", $unix) == $month){ // keep looping/output of while it's correct month
Echo date("d/m/Y", $unix-86400) . "\n"; // Sunday of previous week
Echo date("d/m/Y", $unix) ." - "; // this week's monday
$unix = $unix + (86400*7);
}
Echo date("d/m/Y", strtotime("last day of ".$year . "-" . $month)); //echo last day of month
https://3v4l.org/LAMBl
Here is your solution
$month = $_GET['month'];
if($month<10)$month = '0'.$month;
$year = $_GET['year'];
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year);
$start = 1; $end = 5;
function get_week_array($start,$end){
global $month, $year,$days;
for($i=0;$i<$end;$i++){
if($start<10)$array[] = '0'.$start.'/'.$month.'/'.$year;
else $array[] = $start.'/'.$month.'/'.$year;
$start = $start+1;
if($start==$days+1)break;
}
return $array;
}
$total = 0;
while($days>$total){
$week[] = get_week_array($start,$end);
$total = $total+$end;
$start = $total+1;
$end = 7;
}
echo "<pre>";print_r($week);
Output
Array
(
[0] => Array
(
[0] => 01/02/2017
[1] => 02/02/2017
[2] => 03/02/2017
[3] => 04/02/2017
[4] => 05/02/2017
)
[1] => Array
(
[0] => 06/02/2017
[1] => 07/02/2017
[2] => 08/02/2017
[3] => 09/02/2017
[4] => 10/02/2017
[5] => 11/02/2017
[6] => 12/02/2017
)
[2] => Array
(
[0] => 13/02/2017
[1] => 14/02/2017
[2] => 15/02/2017
[3] => 16/02/2017
[4] => 17/02/2017
[5] => 18/02/2017
[6] => 19/02/2017
)
[3] => Array
(
[0] => 20/02/2017
[1] => 21/02/2017
[2] => 22/02/2017
[3] => 23/02/2017
[4] => 24/02/2017
[5] => 25/02/2017
[6] => 26/02/2017
)
[4] => Array
(
[0] => 27/02/2017
[1] => 28/02/2017
)
)
Try this:
<?php
$month = 12;
$year = 2017;
$date = new DateTime($year.'-'.$month.'-01');
$count = 1;
$week[$count]['start'] = $date->format('Y-m-d');
while (1) {
$date->modify('+1 day');
if ($date->format('m') != $month) {
$week[$count]['end'] = $date->format('Y-m-d');
break;
}
if ($date->format('D') === 'Sun') {
$week[$count++]['end'] = $date->format('Y-m-d');
}
if ($date->format('D') === 'Mon') {
$week[$count]['start'] = $date->format('Y-m-d');
}
}
print_r($week);
This method can show weeks including day of week to break that week
Show test
$month = '2';
$year = '2017';
$lastDayOfWeek = '7'; //1 (for monday) to 7 (for sunday)
function getWeeksInMonth($year, $month, $lastDayOfWeek)
{
$aWeeksOfMonth = [];
$date = new DateTime("{$year}-{$month}-01");
$iDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$aOneWeek = [$date->format('Y-m-d')];
$weekNumber = 1;
for ($i = 1; $i <= $iDaysInMonth; $i++)
{
if ($lastDayOfWeek == $date->format('N') || $i == $iDaysInMonth)
{
$aOneWeek[] = $date->format('Y-m-d');
$aWeeksOfMonth[$weekNumber++] = $aOneWeek;
$date->add(new DateInterval('P1D'));
$aOneWeek = [$date->format('Y-m-d')];
$i++;
}
$date->add(new DateInterval('P1D'));
}
return $aWeeksOfMonth;
}
$weeks = getWeeksInMonth($year, $month, $lastDayOfWeek);
foreach($weeks as $weekNumber => $week){
echo "Week {$weekNumber}: {$week[0]} - {$week[1]}\r\n";
}
Output
Week 1: 2017/02/01 - 2017/02/05
Week 2: 2017/02/06 - 2017/02/12
Week 3: 2017/02/13 - 2017/02/19
Week 4: 2017/02/20 - 2017/02/26
Week 5: 2017/02/27 - 2017/02/28
I want an array of containing weeks of current month, How can i get this? I have tried different methods but none of them is working for me..
$month = date('m'); // it should be CURRENT MONTH Of Current Year
$year = date('y'); // Current year
$beg = (int) date('W', strtotime("$year-$month"));
$end = (int) date('W', strtotime("$year-$month"));
I have used the above code but not working..
I want to put those week numbers of current month into an array like
array ('1' => 'first week of march', '2' => '2nd week of march', '3' => '3rd week of march', '4' => '4th week of march', '5' => '5th week of march' ) etc
1,2,3,4,5 in array can be week number
For getting beginning and ending ISO week number use below code:
$beg = (int) date('W', strtotime(date("Y-m-01")));
$end = (int) date('W', strtotime(date("Y-m-t")));
function weeksOfMonth($month, $year){
$num_of_days = date("t", mktime(0,0,0,$month,1,$year));
$lastday = date("t", mktime(0, 0, 0, $month, 1, $year));
$no_of_weeks = 0;
$count_weeks = 0;
while($no_of_weeks < $lastday){
$no_of_weeks += 7;
$count_weeks++;
}
return $count_weeks;
}
echo weeksOfMonth(3, 2017);
After some hard time looking for it, Here is the Answer, Sorry for posting a bit late here. I hope it will help you guys.
public static function getWeeksOfMonth()
{
$currentYear = date('Y');
$currentMonth = date('m');
//Substitue year and month
$time = strtotime("$currentYear-$currentMonth-01");
//Got the first week number
$firstWeek = date("W", $time);
if ($currentMonth == 12)
$currentYear++;
else
$currentMonth++;
$time = strtotime("$currentYear-$currentMonth-01") - 86400;
$lastWeek = date("W", $time);
$weekArr = array();
$j = 1;
for ($i = $firstWeek; $i <= $lastWeek; $i++) {
$weekArr[$i] = 'week ' . $j;
$j++;
}
return $weekArr;
}
The Result will be the weeks of current Month..
Array (
[26] => week 1
[27] => week 2
[28] => week 3
[29] => week 4
[30] => week 5
[31] => week 6
)
I'm a new to PHP and don't know if my request is possible:
I'd need to get an array with the days of the current week and also indicate for each day if it's the first, second, third, fourth or fifth occurrence of that date for the month.
Examples
For the 1st week of August 2016, it would be:
monday1
tuesday1
wednesday1
thursday1
friday1
saturday1
sunday1
But for the last week of August 2016 (which begins in August and ends in September) it would be:
monday5
tuesday5
wednesday1
thursday1
friday1
saturday1
sunday1
I tried this, but it only works for the current day.
$week_of_the_month = ceil(date('d', $time)/7);
$jd = cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
echo jddayofweek($jd,1).$week_of_the_month;
$d = new DateTime();
$days = [];
for ($i = 0; $i < 7; $i++) {
$date = $d->format('j');
$days[$date] = $d->format('l - ') . ceil($date/7);
$d->add(new DateInterval('P1D'));
}
That will work for the current date, but you can test it on weeks that cross over two months by setting a specific date to work with:
$d = new DateTime('2016-08-31');
The result is as follows:
print_r($days);
Array
(
[31] => Wednesday - 5
[1] => Thursday - 1
[2] => Friday - 1
[3] => Saturday - 1
[4] => Sunday - 1
[5] => Monday - 1
[6] => Tuesday - 1
)
If you want the dates to always start on the Monday of the current week, the DateTime constructor allows you to pass in a string as such:
$d = new DateTime('monday this week');
Today is Thursday, but it gives:
Array
(
[1] => Monday - 1
[2] => Tuesday - 1
[3] => Wednesday - 1
[4] => Thursday - 1
[5] => Friday - 1
[6] => Saturday - 1
[7] => Sunday - 1
)
Changing Language
If you want to change the language of the date output, that is a separate topic (see here). You will need to have the locales/extensions installed on your system. If you don't want to go down that route, you could just map the days into your language yourself:
$intlDays = [
'Monday' => 'Lundi',
'Tuesday' => 'Mardi',
'Wednesday' => 'Mercredi',
'Thursday' => 'Jeudi',
'Friday' => 'Vendredi',
'Saturday' => 'Samedi',
'Sunday' => 'Dimanche'
];
$d = new DateTime('monday this week');
$days = [];
for ($i = 0; $i < 7; $i++) {
$date = $d->format('j');
$output = $d->format('l - ') . ceil($date/7);
$output = str_replace(array_keys($intlDays), $intlDays, $output);
$days[$date] = $output;
$d->add(new DateInterval('P1D'));
}
I have fetched a current month from my DB which is basically a join date of the user. Lets say the use joined this month and it is May. The code I do to fetch the month name is like this:
$months = array();
array_push($months,date("F",strtotime($me['joinTime'])));
In this case I add the start month to the array, which in this case is May... Now what I'd like to do is as the months go by, I'd like to add each new month to the array.. So for instance in a few days its June, and when June kicks in, I'll add that Month as well to the array.. So my question here is, how can I get the rest of the month names from the start date (May).
I need June, July, August, September, October, November, December...
If the start month was April I'd add May into the array as well...
Can someone help me out with this ?
First you need to get he month number and than you need to use a loop through to end of the year that is 12. For each month number you also need the month name so use DateTime createFromFormat.
Online Check
$months = array();
$num = date("n",strtotime($me['joinTime']));
array_push($months, date("F", strtotime('2016-05-17 16:41:51')));
for($i = ($num + 1); $i <= 12; $i++){
$dateObj = DateTime::createFromFormat('!m', $i);
array_push($months, $dateObj->format('F'));
}
print_r($months); // Array ( [0] => May [1] => June [2] => July [3] => August [4] => September [5] => October [6] => November [7] => December )
Yo can also put it like
$array = array();
array_push($array, date('F')) ;
for ($i=1; $i<= 12 - date('m'); $i++ ){
array_push($array, date('F', strtotime("+$i months"))) ;
}
print "<pre>";print_r($array);
Here we will be using DatePeriod which allows iteration over a set of dates and times, recurring at regular intervals, over a given period.
So we got the end date and we have the start date and then calculated the interval. And then looping over the period we got the array of months.
// current date : 20 Feb 2019
$startDate = new \DateTime('first day of next month');
$endDate = new \DateTime('1st january next year');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($startDate, $interval, $endDate);
// Start array with current date
$dates = [];
// Add all remaining dates to array
foreach ($period as $date) {
array_push($dates, $date->Format('F'));
}
// output
print_r($dates); die;
Array ( [0] => March [1] => April [2] => May [3] => June [4] => July [5] => August [6] => September [7] => October [8] => November [9] => December )