Can I use an if statement with multiple conditions? PHP - php

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 ||

Related

Split numbers and words from user supplied data

I have the following code on my index.php file
<?php
$string = $_GET['string'];
$month = '';
$day = '';
?>
If string is like "apr12" or "12apr",
then $month should be "apr" and $day should be "12"
else both $month & $day should be blank.
You can use the fact that day is only numbers and month is only chars, so it may look like this:
$string = $_GET['string'];
$month = strtolower(preg_replace('/[^a-z]+/i','',$string));
$day = preg_replace('/[^0-9]+/','',$string);
if (!in_array($month, ['jan'/* ... and other valid values */], true)) {
$month = '';
}
if ($day === '' || (int)$day < 1 || (int)$day > 31) {
$day = '';
}
// Then validate your input further

Start counting weeks from specific month

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.

Php datetime function doesn't recognise dates before 1000

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

Remove passed dates in CodeIgniter Calendar

Is it possible to remove the dates that have already passed (in the past) in Codeigniter Calendar?
I'm using the Calendar Template that was provided in the user's manual
This is possible although I don't know if it is conventional here is my code.
Save to "/application/libraries/MY_Calendar.php"
<?php
class MY_Calendar extends CI_Calendar {
/**
* Generate the calendar
*
* #param int the year
* #param int the month
* #param array the data to be shown in the calendar cells
* #return string
*/
public function generate($year = '', $month = '', $data = array()) {
$local_time = time();
// Set and validate the supplied month/year
if (empty($year)) {
$year = date('Y', $local_time);
} elseif (strlen($year) === 1) {
$year = '200' . $year;
} elseif (strlen($year) === 2) {
$year = '20' . $year;
}
if (empty($month)) {
$month = date('m', $local_time);
} elseif (strlen($month) === 1) {
$month = '0' . $month;
}
$adjusted_date = $this->adjust_date($month, $year);
$month = $adjusted_date['month'];
$year = $adjusted_date['year'];
// Determine the total days in the month
$total_days = $this->get_total_days($month, $year);
// Set the starting day of the week
$start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6);
$start_day = isset($start_days[$this->start_day]) ? $start_days[$this->start_day] : 0;
// Set the starting day number
$local_date = mktime(12, 0, 0, $month, 1, $year);
$date = getdate($local_date);
$day = $start_day + 1 - $date['wday'];
while ($day > 1) {
$day -= 7;
}
// Set the current month/year/day
// We use this to determine the "today" date
$cur_year = date('Y', $local_time);
$cur_month = date('m', $local_time);
$cur_day = date('j', $local_time);
$is_current_month = ($cur_year == $year && $cur_month == $month);
// Generate the template data array
$this->parse_template();
// Begin building the calendar output
$out = $this->replacements['table_open'] . "\n\n" . $this->replacements['heading_row_start'] . "\n";
// "previous" month link
if ($this->show_next_prev === TRUE) {
// Add a trailing slash to the URL if needed
$this->next_prev_url = preg_replace('/(.+?)\/*$/', '\\1/', $this->next_prev_url);
$adjusted_date = $this->adjust_date($month - 1, $year);
$out .= str_replace('{previous_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->replacements['heading_previous_cell']) . "\n";
}
// Heading containing the month/year
$colspan = ($this->show_next_prev === TRUE) ? 5 : 7;
$this->replacements['heading_title_cell'] = str_replace('{colspan}', $colspan,
str_replace('{heading}', $this->get_month_name($month) . ' ' . $year, $this->replacements['heading_title_cell']));
$out .= $this->replacements['heading_title_cell'] . "\n";
// "next" month link
if ($this->show_next_prev === TRUE) {
$adjusted_date = $this->adjust_date($month + 1, $year);
$out .= str_replace('{next_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->replacements['heading_next_cell']);
}
$out .= "\n" . $this->replacements['heading_row_end'] . "\n\n"
// Write the cells containing the days of the week
. $this->replacements['week_row_start'] . "\n";
$day_names = $this->get_day_names();
for ($i = 0; $i < 7; $i++) {
$out .= str_replace('{week_day}', $day_names[($start_day + $i) % 7], $this->replacements['week_day_cell']);
}
$out .= "\n" . $this->replacements['week_row_end'] . "\n";
// Build the main body of the calendar
while ($day <= $total_days) {
$out .= "\n" . $this->replacements['cal_row_start'] . "\n";
for ($i = 0; $i < 7; $i++) {
if ($day > 0 && $day <= $total_days) {
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start'];
if ($day < date('d')) {
$out .= ' ';
} elseif (isset($data[$day])) {
// Cells with content
$temp = ($is_current_month === TRUE && $day == $cur_day) ?
$this->replacements['cal_cell_content_today'] : $this->replacements['cal_cell_content'];
$out .= str_replace(array('{content}', '{day}'), array($data[$day], $day), $temp);
} else {
// Cells with no content
$temp = ($is_current_month === TRUE && $day == $cur_day) ?
$this->replacements['cal_cell_no_content_today'] : $this->replacements['cal_cell_no_content'];
$out .= str_replace('{day}', $day, $temp);
}
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_end_today'] : $this->replacements['cal_cell_end'];
} elseif ($this->show_other_days === TRUE) {
$out .= $this->replacements['cal_cell_start_other'];
if ($day <= 0) {
// Day of previous month
$prev_month = $this->adjust_date($month - 1, $year);
$prev_month_days = $this->get_total_days($prev_month['month'], $prev_month['year']);
$out .= str_replace('{day}', $prev_month_days + $day, $this->replacements['cal_cell_other']);
} else {
// Day of next month
$out .= str_replace('{day}', $day - $total_days, $this->replacements['cal_cell_other']);
}
$out .= $this->replacements['cal_cell_end_other'];
} else {
// Blank cells
$out .= $this->replacements['cal_cell_start'] . $this->replacements['cal_cell_blank'] . $this->replacements['cal_cell_end'];
}
$day++;
}
$out .= "\n" . $this->replacements['cal_row_end'] . "\n";
}
return $out .= "\n" . $this->replacements['table_close'];
}
}
You can see my code diverges from native at line 108 with this snippet:
... if ($day < date('d')) {
$out .= ' ';
} ...
As far as pagination, future months, and past months you will need to modify the snippet as you see fit.
The answer below from William Knauss works out of the box (kudos to you William).
I actually went a little further with it and adapted William's solution to my needs.
Basically I wanted the days in the past to be disabled. As in, I wanted to put a class i the the td element for days in the past and a different class for the elements in the future (including today).
So, the code starting on line 106 looks as follows:
if ($day < date('d')) {
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start_past'];
}else{
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start'];
}
if (isset($data[$day])) { // this part was restored to the way it is in the native class.
// Cells with content...
Notice the 'cal_cell_start_past'. This is a new array property in the default_template array in the native class. Starting in line 473.
Now it looks like this:
'cal_row_start' => '<tr>',
'cal_cell_start_past' => '<td class="pastDay">',
'cal_cell_start' => '<td class="day">',
'cal_cell_start_today' => '<td class="day">',
Hope this helps someone else.

How to express the difference between two dates in a human-readable format

If I have two dates - $end_date and $start_date, how can I express the difference between the two in a format such as "2 Years : 4 Months : 2 Days"?
I know that I can get the difference between the two dates like so:
$dif=strtotime($end_date)-strtotime($today);
But how can I convert that result into the human-readable format, like that shown above?
This is how you can format a timestamp:
echo date('d-m-Y', strtotime($end_date)) // for DD-MM-YYYY format
Are you looking to calculate the difference between 2 dates, in number days?
EDIT: code to find the difference between dates in "XXyear YYmonth ZZday". The code assumes that start and end dates are in YYYY-MM-DD format. If that's not the case for you, please either change them to YYYY-MM-DD format, OR change the arguments to mktime() accordingly.
$endDate = '2011-03-01';
$startDate = '2011-02-02';
$daysPerYear = 365;
$daysPerMonth = 30.4;
$diffDay = $diffMonth = $diffYear = 0;
$endDateTs = mktime(0, 0, 0, substr($endDate, 5, 2), substr($endDate, 8, 2), substr($endDate, 0, 4));
$startDateTs = mktime(0, 0, 0, substr($startDate, 5, 2), substr($startDate, 8, 2), substr($startDate, 0, 4));
$diffDay = ($endDateTs - $startDateTs) / 60 / 60/ 24; // difference between 2 dates in number of days
$diffYear = floor($diffDay / $daysPerYear); // difference in years
$diffDay = $diffDay % $daysPerYear; // balance days
$diffMonth = floor($diffDay / $daysPerMonth); // difference in months
$diffDay = ceil($diffDay % $daysPerMonth); // balance days
echo ($diffYear ? $diffYear . 'year ' : '') . ($diffMonth ? $diffMonth . 'month ' : '') . ($diffDay ? $diffDay . 'day' : '');
Note: I haven't tested the code for all possible date combinations, including leap year etc. Please feel free to tweak as needed.
Hope this helps.
If a coarse difference is enough ("2 years ago"), then you might want to try the Date_HumanDiff PEAR package.
The clean, DRY, professional, modern way to do this is to create two datetime objects and call diff(). The generated diff object will automatically populate year, month, day values for you.
Then you only need to iterate through a lookup array containing your desired units and implode any non-zero results into the plain English output string.
Code (Demo)
$startDate = '2001-04-20';
$endDate = '2015-11-29';
$diff = (new DateTime($startDate))->diff(new DateTime($endDate));
$lookup = [
'y' => 'Year',
'm' => 'Month',
'd' => 'Day',
];
$elements = [];
foreach ($lookup as $property => $word) {
if ($diff->$property) {
$elements[] = "{$diff->$property} $word" . ($diff->$property !== 1 ? 's' : '');
}
}
echo implode(' : ', $elements);
// 14 Years : 7 Months : 9 Days
function is_leap_year($year)
{
if($year % 4 == 0)
{
if($year % 100 == 0)
{
if($year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
function calculate_date($now, $end){
$years = date('Y', strtotime($end)) - date('Y', strtotime($now)) ;
if($years < 0)
{
return "Error: year";
}
$mounths = date('m', strtotime($end)) - date('m', strtotime($now)) ;
if($mounths < 0)
{
if($years < 1)
{
return "Error: mounth and year";
}
else
{
$years --;
$mounths += 12;
}
}
$days = date('d', strtotime($end)) - date('d', strtotime($now)) ;
if($days < 0){
if($mounths < 1)
{
if($years < 1)
{
return "Error: day, mounth and year";
}
else
{
$years --;
$mounths += 12;
}
}
else
{
$mounths --;
switch (date('m', strtotime($now)))
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
$days +=31;
break;
case 4:
case 6:
case 9:
case 11:
$days +=30;
break;
case 2:
if(is_leap_year(date('Y', strtotime($now))))
{
$days += 29;
break;
}
else
{
$days += 28;
break;
}
}
}
}
return $years . " Years : " . $mounths . " Months : " . $days . " Days Remaining.";
}
$end_date = new DateTime('2011-08-05');
$end_date = $end_date->format('d-m-Y');
$today = date('d-m-Y');
$remaining = calculate_date($today, $end_date);
echo $remaining;
And if you want to format end_date you can use:
date('d-m-Y', strtotime($end_date))
And after that you can calculate remaining time with calculate_date .

Categories