Im trying to write php code which would start counting weeks from specific month. For me its September and February. For example desired result for 01.09.2017 would be Semester-1,Week-1. and for 04.09.2017 would be Semester-1,Week-2. I found similar topics here and here . But their output result is array, should i work with arreys here too ? I want to mention that I almost have zero expierence with php language.
This is what I have come up with so far:
<?php
$day = date("D");
$month = date("M");
if($month == 'Apr'||'Feb'||'Mar'||'May') {
print "Semester-2,";
}
else print "";
if($month == 'Sep'||'Oct'||'Nov'||'Dec') {
print "Semester-1,";
}
else print "";
if($month == 'Jan') {
print "Exams";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jun') {
print "Exams,";
}
if($month == 'Jul'||'Aug') {
print "Summer Break,";
}
You could do something like this:
$month = date('n'); // Month number 1-12
if ($month >= 9 && $month <=12) {
$period = 'Semester-1';
$startWeek = date('W', strtotime(date('Y') . '-09-01'));
} elseif ($month >= 2 && $month <=5) {
$period = 'Semester-2';
$startWeek = date('W', strtotime(date('Y') . '-02-01'));
} elseif ($month == 1) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-01-01'));
} elseif ($month == 6) {
$period = 'Exams';
$startWeek = date('W', strtotime(date('Y') . '-06-01'));
} elseif ($month == 7 || $month == 8) {
$period = 'Summer break';
$startWeek = date('W', strtotime(date('Y') . '-07-01'));
}
$currentWeek = date('W') - $startWeek + 1;
echo $period . ' ' . 'Week-' . $currentWeek;
After #Qirel comment, I thought of something like this, hope this helps :
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$month = date("M"); /* current month */
if (in_array($month, array("Sep", "Oct", "Nov", "Dec"))) { $myperiod = "Semester #1"; }
if (in_array($month, array("Feb", "Mar", "Apr", "May"))) { $myperiod = "Semester #2"; }
if($month == 'Jan') { $myperiod = "Mid-Exams #1"; }
if($month == 'Jun') { $myperiod = "Final-Exams #2"; }
if( ($month == 'Jul') || ($month == 'Aug') ) { $myperiod = "Summer break"; }
$today = date("Y-m-d"); /* or use your date from user data */
$date = new DateTime($today);
$week = $date->format("W"); /* use of PHP function 'date' to get week # */
$currentweek = "$week";
echo "[ Week # $week ]";
echo"You currently are in : $myperiod - $currentweek";
?>
This should give you what you need:
$semesters = array(
'Sep' => 'Semester-1',
'Oct' => 'Semester-1',
'Nov' => 'Semester-1',
'Dec' => 'Semester-1',
'Jan' => 'Exams',
'Feb' => 'Semester-2',
'Mar' => 'Semester-2',
'Apr' => 'Semester-2',
'May' => 'Semester-2',
'Jun' => 'Exams',
'Jul' => 'Summer Break',
'Aug' => 'Summer Break',
);
switch ($semesters[date('M')]) {
case 'Semester-1':
$sep1st = strtotime('2017-09-01');
$week1 = date('W', $sep1st);
$currentWeek = date('W');
echo 'Semester-1, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
case 'Semester-2':
$feb1st = strtotime('2018-02-01');
$week1 = date('W', $feb1st);
$currentWeek = date('W');
echo 'Semester-2, Week-', $currentWeek - $week1 + 1; // +1 because the count starts at 1.
break;
default:
echo $semesters[date('M')];
break;
}
Note that this can be refactored into smaller, more semantic parts.
Related
I bet I can, but would it work like this?
function dutchDateNames($) {
$day = explode('-', $date)[2];
$dutchday = ($day < 10) ? substr($day, 1) : $day;
$month = explode('-', $date)[1];
if ($month == '01' . '02') {
$dutchmonth = 'Januari' . 'Februari';
}
$dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
return $dutchdate
}
So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?
Like thatyou would not return any month cause you concatenate (mounth 0102 does not exist).
If i correctly understand your question i think an array will be better :
$month = explode('-', $date)[1]; //Ok you use this data like an index
$letterMonth = ['01' => 'Januari', '02' => 'Februari', ....]; // Create an array with correspondance number -> letter month
$dutchmonth = $letterMonth[$month]; Get the good month using your index
Try this:
Use elseif conditions
if ($month == '01') {
$dutchmonth = 'Januari';
} elseif ($month == '02') {
$dutchmonth = 'Februari';
} elseif ($month == '03') {
$dutchmonth = '...';
}
Create lookup array and get value by key:
$month = '02';
$months = [
'01' => 'Januari'
'02' => 'Februari'
// more months here
];
$dutchmonth = isset($months[$month])? $months[$month] : '';
echo $dutchmonth;
I think the proper way is to save the map a array. Demo
<?php
$array['01'] = 'Januari';
$array['02'] = 'Februari';
print_r($array);
echo $array[$month];
You may do any of these:
if else
if ($month == "01") {
$dutchmonth = "Januari";
} else if($month == "02"){
$dutchmonth = "Februari";
}
switch
switch($month) {
case "01":
$dutchmonth = "Januari";
break;
case "02":
$dutchmonth = "Februari";
break;
}
Using array
$month_arr = array('01' => "Januari", '02' => "Februari");
$dutchmonth = $month_arr[$month];
NOTE: To use multiple if conditions use logical operators && or ||
This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000
I'm trying to list all months between two dates.
For example; start date is: 2010-12-02 and last date is: 2012-05-06
I want to list something like this:
2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05
This is what I have tried and it is not working at all:
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
In Laravel,
$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
October 2021 Update
If you have dates selected by the user, here's a solution
$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));
$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
else {
$current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
$date = date('Y-m-d', $current_date);
$dates[] = $date;
$months[] = date('Y-m', $current_date);
$counter++;
}
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';
I have an event calendar that starts on Sunday. I must change it to start on Monday.
Part of my code:
<html>
<body>
<?php
$dagteller=$firstDayArray["wday"];
$mDay=$firstDayArray["mday"];
define("ADAY", (60*60*24));
$mydate=getdate(date("U"));
define("ADAY", (60*60*24));
for ($count=0; $count < (6*7); $count++) {
$dayArray = getdate($start);
if (($count % 7) == 0) {
if ($dayArray["mon"] != $month) {
break;
} else {
echo ("</tr ><tr>\n");
}
}
if ((!isset($_POST['month'])) || (!isset($_POST['year']))) {
$nowArray = getdate();
$month = $nowArray['mon'];
$year = $nowArray['year'];
$day = $nowArray['day'];
} else {
$month = $_POST['month'];
$year = $_POST['year'];
}
// on my table
echo ("<td bgcolor=\"#DDDDDD\"><center>".$dayArray["mday"]."</center></td>\n");
$start += ADAY;
?>
</body>
</html>
Read the PHP date manual for yourself:
http://www.php.net/manual/en/function.date.php
The 'W' identifier will help you
I'm trying to list all months between two dates.
For example; start date is: 2010-12-02 and last date is: 2012-05-06
I want to list something like this:
2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05
This is what I have tried and it is not working at all:
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
In Laravel,
$period = \Carbon\CarbonPeriod::create('2017-06-28', '1 month', '2019-06-01');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
October 2021 Update
If you have dates selected by the user, here's a solution
$from = date('Y-m-d', strtotime($_POST['from']));
$to = date('Y-m-d', strtotime($_POST['to']));
$counter = 1;
$max_date = strtotime($to);
$current_date = strtotime($from);
$dates = [];
$months = [];
$loop = true;
while($loop) {
if(strtotime(date('Y-m-d',$current_date)." +".$counter."days") >= $max_date) $loop = false;
else {
$current_date = strtotime(date('Y-m-d', $current_date)." +".$counter."days");
$date = date('Y-m-d', $current_date);
$dates[] = $date;
$months[] = date('Y-m', $current_date);
$counter++;
}
}
$months = array_unique($months);
echo '<pre>';
print_r($dates);
echo '<br>';
print_r($months);
echo '</pre>';