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.
Related
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 need to get yesterday's date to show the market close date. This only applies to Monday through Friday as the markets are not open on the weekend. Using this format how would I do that?
<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>
Here's one way to do it:
$date= new \DateTime();
$oneDay = new \DateInterval('P1D');
$date->sub($oneDay);
if ('Sunday' === $date->format('l')) {
$date->sub($oneDay);
}
if ('Saturday' === $date->format('l')) {
$date->sub($oneDay);
}
echo $date->format('Y-m-d');
I just get today's date, subtract one day, and check to see if it is a Sunday. If so, subtract a day. Then I do the same thing for a Saturday. Ultimately you end up with the last weekday.
Keep in mind this is different then business day's as that Friday may be a holiday and the markets may be closed.
You could check what day the current week day is with date('w').
Note that Sunday is 0, and Saturday is 6.
And with that information, you can do:
$yesterday = strtotime(date('w') == 0 || date('w') == 6 ? 'last friday' : 'yesterday');
echo date('Y-m-d', $yesterday);
Basically, if it's a weekend, you ask for the last friday, otherwise, you ask PHP for yesterday.
If you don't like it in one line:
$w = date('w');
if($w == 0 || $w == 6)
$yesterday = strtotime('last friday');
else
$yesterday = strtotime('yesterday');
$yesterday = date('Y-m-d', $yesterday);
In our case today, Tuesday, June 14th 2016, it will return 2016-06-13.
For more information about the date function: http://php.net/manual/en/function.date.php
Is there a short preset function to find the start (Monday) and end (Sunday) of the week by a given $date ?
I tried:
1)
date("Y-m-d", strtotime('sunday this week ' . $date));
date("Y-m-d", strtotime('monday this week ' . $date));
But this fails when $date is Sunday... it returns the Monday of Next week.
2) also this
date("Y-m-d", strtotime('last monday ' . $date));
date("Y-m-d", strtotime('next sunday ' . $date));
But again if $date is Monday or Sunday it gives the previous/next week.
I know it can be done with few condition .. but I m look for more out of the box solution.
You can use DateTime::format('N') to get the ISO-8601 day of the week (1 = Monday .. 7 = Sunday) and do some simple date arithmetic to get the Monday and the Sunday of the week that contains the specified date (I assume you want the week starting on Monday).
// Today (or any other day you like)
$today = new DateTime('now');
echo('Today: '.$today->format('Y-m-d (D)')."\n");
// Day of week (1 = Monday .. 7 = Sunday)
$dow = $today->format('N');
// Monday is ($dow-1) days in the past
$monday = clone $today;
$monday->sub(new DateInterval('P'.($dow-1).'D'));
echo('Monday: '.$monday->format('Y-m-d')."\n");
// Sunday is 6 days after Monday
$sunday = clone $monday;
$sunday->add(new DateInterval('P6D'));
echo('Sunday: '.$sunday->format('Y-m-d')."\n");
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." ;
}
}
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"