My previous question: how-to-find-current-day-no-in-month-in-php
Now I face another problem. Suppose I know that this monday is the 4th monday of the current month. Now how to check that this monday is also the last monday of the current month?
exa:1
date: 27-01-2014
Using the code below, I get the name and number of a day:
day: monday
day no :4th
This is the 4th monday of january and it is also the last monday of january. How to check that?
exa:2
date: 20-01-2014
day: monday
day no :3rd
Here this monday is 3rd monday of january but not last monday of january.
So, in short, when I got a day number then how to check whether that the day number is last or not?
code:
$t=date('d-m-Y');
$dayName = strtolower(date("D",strtotime($t)));
$dayNum = strtolower(date("d",strtotime($t)));
$dayno = floor(($dayNum - 1) / 7) + 1
The quickest way to check if today is the last of the month I would suggest the following
if(date('t') == date('d')){
echo 'Last day of the month.';
}
This compares the current day with the number of days of the current month.
Just add 7 days (you still have a monday) to the date you have, and check if it's in the same month.
The complete solution is as follow. Thanks to #Oliver M Grech and #Nanne.
$t=date('d-m-Y');
$day = strtolower(date("D",strtotime($t)));
$month = strtolower(date("m",strtotime($t)));
$dayNum = strtolower(date("d",strtotime($t)));
$weekno = floor(($dayNum - 1) / 7) + 1;
if($weekno=="4" or $weekno=="5")
{
$Date = date("d-m-Y");
$new_month = date('m', strtotime($Date. ' + 7 days'));
if($new_month != $month)
{
echo "This ".$day." is last day of month." ;
}
}
Related
I should be able to get the first Wednesday of each month, I can do it easily using:
$firstWedNextMonth = date ('d-m-Y', strtotime('first wednesday of next month'));
echo "The first wed of next month is: ".$firstWedNextMonth;
However, considering that the first Wednesday of next month is March 6th, the system must show this date until 3:00:00 on Thursday March 7th, at 3:00:01 instead it must indicate Wednesday, April 3rd. I do not know how to do it. Thank you
I think, this should work. +27 hours is 24 hours + your margin (3 hours). You can test it setting $now to whatever you want, instead of the current time.
$now = time();
$firstWedThisMonth = date ('d-m-Y', strtotime('first wednesday of this month', $now));
$firstWedNextMonth = date ('d-m-Y', strtotime('first wednesday of next month', $now));
$boundaryDateTime = strtotime('+27 hours', strtotime($firstWedThisMonth));
if ($now <= $boundaryDateTime) {
echo "The first wed of next month is: ".$firstWedThisMonth;
} else {
echo "The first wed of next month is: ".$firstWedNextMonth;
}
I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks
Try this:
$week = intval(date('W'));
if (date('w') == 0) { // 0 = Sunday
$week++;
}
echo $week;
Not sure if the logic is right though;
The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );
To expand on silkfire answer and allow for it wrapping around years
if($date->format('w') == 0){
if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
$week = 1;
}
elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
$week = 1;
}
else{
$week++;
}
}
Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));
You should try with strftime
$week_start = new DateTime();
$week = strftime("%U"); //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting
I solved this like this:
function getWeekOfYear( DateTime $date ) {
$dayOfweek = intval( $date->format('w') );
if( $dayOfweek == 0 ) {
$date->add(new DateInterval('P1D'));
}
$weekOfYear = intval( $date->format('W') );
return $weekOfYear;
}
I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));
I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)
if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
$week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
$week = date("W",$week);
}else{ // if is not monday
$week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
$week = date("W",$week);
}
Building on #silkfire's answer:
$year = date('Y');
$week_no = date('W');
if (date('w') == 0) { // 0 = Sunday
$week_no++;
}
// We shifted the week but the week still starts on a Monday.
$weekStartDate = new DateTime();
$weekStartDate->setISODate($year,$week_no);
// Shift start date to Sunday
$weekStartDate->add(DateInterval::createFromDateString('-1 day'));
Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
$week = intval($_date->format('W'));
if(intval($_date->format('w')) == 0) {
$week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
}
return $week;
}
I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));
I am trying to query results from last week from Thursday to Wednesday.
Today is the 18th which is Sunday, the first day of the week in PHP terms. My Code is not working because it restarts on Sunday. My IF statement is not working and my week modifier (-1 Week) is not working. Every week should go from thursday to thursday which ends at midnight on Wednesday. The results I am getting is today's results, but it should be going back to just this last thursday, subtracting -1 week, and pulling those results ending just this last thursday.
It should be pulling data between these dates
2015-1-8 thru
2015-1-14
But it's pulling from 2015-1-15 thru 2015-1-21 and not suppose to.
<div class="subtitle">Last Week (12AM Thur to 12AM Thur)</div>
<div class="totamt">$<?php
require_once 'wp-content/themes/azure-basic/connectvars.php';
$dbc = mysqli_connect(CDB_HOST, CDB_USER, CDB_PASSWORD, CDB_NAME);
/* Last Week */
$twoWeeksAgoStart = new DateTime("Thursday last week");
$twoWeeksAgoEnd = new DateTime("Wednesday");
$today = new DateTime("now");
$day = $today->format("1");
if ($day == "Sunday" || $day == "Monday" || $day == "Tuesday" || $day == "Wednesday") {
//This DOES NOT WORK from Sunday to Wednesday
$twoWeeksAgoStart->modify("- 1 week");
$twoWeeksAgoEnd->modify("- 1 week");
} else {
//This DOES actually works on Thursday through Saturday Night
$twoWeeksAgoStart->modify("+7 days");
$twoWeeksAgoEnd->modify("- 1 week");
}
$startdates = $twoWeeksAgoStart->format( 'Y-m-d' );
$enddates = $twoWeeksAgoEnd->format('Y-m-d');
$query = "SELECT SUM(amountoffeeearned) as totalamount FROM commissioninfo WHERE thedate BETWEEN '$startdates' AND '$enddates'";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
?>
I did some light testing, and I believe this may work for you:
if(date('N') == 4){
$startdates = date("Y-m-d", strtotime("last Thursday"));
$enddates = date("Y-m-d", strtotime("-1 day"));
}else{
$startdates = date("Y-m-d", strtotime("last Thursday -1 week"));
$enddates = date("Y-m-d", strtotime("last Thursday - 1 day"));
}
It checks if today is Thursday and if it is then it uses "last Thursday" and the current day -1 day to get the week. Any other day, it uses last Thursday - 1 week and last Thursday - 1 day to get the timeframe. As if today were say Friday the 23rd, in PHP's mind last Thursday is the day before (the 22nd) and on Thursday last Thursday is the preceding week's Thursday.
Hope this works and helps!
I haven't tested it thoroughly but it might worth the try. Let me know if it works:
$minus = (date('D') !== 'Thu') ? "-1 week" : "";// Thursday check
$startdates = date("Y-m-d", strtotime("$minus last Thursday"));
$enddates = date("Y-m-d", strtotime("last Wednesday"));
Hope it helps.
How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)
One way to achieve this is using relative formats for strtotime().
Unfortunately, it's not as straightforward as:
strtotime('Friday of second week of September 2013');
In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.
$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13
Note: Since the first day of the month starts on week one, I've decremented the week accordingly.
I was going to suggest to just use strtotime() in this fashion:
$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13
It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)
This way its a little longer and obvious but it works.
/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;
$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
$result = date("d", $start);
break;
}
$start += 60 * 60 * 24;
}
var_dump($result); // string(2) "06"
I have a PHP calendar that lists all of the days of the month in a table. Before the first day of the month I have numbers from the prior month and after the last day of the month are the numbers of the days for the upcoming month.
Here's a photo of the Calendar as it currently looks. As you can see the bottom gray numbers are working fine, but the numbers preceding the first day of the month are negative numbers and should instead appear as '29,30'
The numbers after the last day of the month were simply '32,33,34' for example, so I just created an if statement that checks if the number is greater than the total numbers of days in the current month and if so, then subtract the total numbers of days in the month from '32' for example, which would then make it appear as '1,2,3'.
if ($day > $total_days_of_current_month) {
echo '<td>' . ($day - $total_days_of_current_month) . ' </td>'; // for example,33-31=2
}
My problem is creating an if statement that somehow knows what the last days of the prior month was. The problem is that some months have 30 days and some have 31 days. Also, the month of February and leap years are a problem. Does anyone know an if statement so i can make it appear as '28,29,30' from the previous month?
Perhaps this can help?
cal_days_in_month()
(Edited to include inshalla's feedback)
Assuming $day is a UNIX timestamp:
// gets you the first of the month
$date = getdate(mktime(0, 0, 0, date('n', $day), 1, date('Y', $day)));
From here, do one of these:
$lastDayOfPrevMonth = strtotime('-1 day', $date[0]);
// or, better, get the first day "in the grid" (assuming week starts on Sunday)
$date = strtotime("-$date[wday] days", $date[0]);
I don't want to harp on it, but have you looked at my previous answer? That's a more robust way to build a calendar instead of all this special case checking.
Why not just take the timestamp of the first day of the month, and subtract 24 hours from it and then use date('d', $timestamp); ? Also, if you have a timestamp in that month, date('t', $timestamp); will get the number of days in the month for you.
A quick example:
// sets to 3am, first day of month, 3am helps us avoid DST issues with subtracting hours
$monthStart = mktime(3,0,0,date('n'),1,date('Y'));
$thisMonth = date('n', $monthStart);
// rewind to the sunday before- date('w') is the "weekday" 0 based
$date = $monthStart - (date('w',$monthStart) * 60 * 60 * 24);
while ($date<$monthStart || date('n', $date) == $thisMonth)
{
echo "<tr>";
for ($x=0; $x<7; $x++) {
echo "<td";
if (date('n', $date) != $thisMonth) echo " class='notMonth'";
echo ">";
echo date("j", $date);
echo "</td>";
$date += 60*60*24;
}
echo "</tr>\n";
}
Take a look at the source of PHP-Calender-Class Project:
http://code.google.com/p/php-calendar-class/
class source: http://code.google.com/p/php-calendar-class/source/browse/trunk/calendar.class.php
It may give you some insight on the problem.
Using cal_days_in_month(), How about adding the following code:
if ($day < 1) {
echo '<td>' . ($day + cal_days_in_month(
CAL_GREGORIAN,date_format("n",
date_add(date_create(),"P-1M")))) . ' </td>'; // for example,-1 + 30 = 29th
}
EDITED: Added the date_format function
Wait a minute... your month name at the top is wrong! It says "August 2009", but the month has 30 days and the weekdays are right for September 2009!
You need to repair the current month first, before worrying about other months.