Is there a function to calculate weekdays from today PHP - php

I'm writing a code which need to calculate the number of weekdays from a date to today.
I just have today's date and with that i want to pass a number to the function so it can return me back the number of weekdays since x days.
e.g :
function getWorkingDays($number){
// code...
return $value;
}
// if we are monday
getWorkingDays(2) // return Thursday's date
I got this problem since two days now and i'm getting very boring, hope someone got a solution.

This is very easy to do with the DateTime object:
$date = date_create('2020-01-06'); //a Monday
$numberWeekdays = 2;
$date->modify('-'.$numberWeekdays.' weekdays');
echo $date->format('l Y-m-d');
//Thursday 2020-01-02
If you need Today as the basis , you can also use date_create('Today').

Related

Last week of year and 1st January with Carbon?

I'm working on a project and I need to format date in the following : YYYYWW where WW is the week number in the year, for example : today is 202131.
There are several ways to do this, I can use isoFormat('YYYYWW') directly, or I can get weekOfYear attribute and append it to current year.
Both methods however, break for the following date : 01-01-2021, indeed, the 1st january is set in the last week of 2020, but the year is 2021. Both methods give : 202153 while the correct result should be 202053 .
I currently have a workaround by checking if the month is less than 3 and the week is bigger than 50 then there is a problem and I decrement the year by 1.
public static function formatTestWeek($d)
{
$current = Carbon::parse($d);
$currentWeek = $current->weekOfYear;
$currentYear = $current->year;
if($currentWeek > 50 && $current->month < 3){
$currentYear -= 1;
}
$formattedDate = strval($currentYear) . $current->isoFormat("WW");
return $formattedDate;
}
Is there a more elegant approach in Carbon to get YYYYWW format that works in all cases ?
YYYY is the year
GGGG is the ISO week-year
gggg is the week-year following current locale settings (first_day_of_week + day_of_first_week_of_year)
So you need ->isoFormat('GGGGWW')
Complete list of codes available in isoFormat() are in the documentation:
https://carbon.nesbot.com/docs/#iso-format-available-replacements

PHP: How to know if a date is in the current month?

I need to know if a date is in the current month.
Examples:
If the date is 2018-06-30 and current month is June (06), then true.
If the date is 2018-07-30 and current month is June (06), then false.
I have a list of dates with more than 1000 dates and I want to show or colorize only the dates that belongs to a current month.
You can do it all on one line. Basically convert the date in question to a PHP time, and get the month.
date('m',strtotime('2018-06-30' )) == date('m');
Using the date() function, if you pass in only the format, it'll assume the current date/time. You can pass in a second optional variable of a time() object to use in lieu of the current date/time.
I hope this helps -
$date = "2018-07-31";
if(date("m", strtotime($date)) == date("m"))
{
//if they are the same it will come here
}
else
{
// they aren't the same
}
As an alternative you could use a DateTime and for the format use for example the n to get the numeric representation of a month without leading zeros and use Y to get the full numeric representation of a year in 4 digits.
$d = DateTime::createFromFormat('Y-m-d', '2018-06-30');
$today = new DateTime();
if($d->format('n') === $today->format('n') && $d->format('Y') === $today->format('Y')) {
echo "Months match and year match";
}
Test
PHP doesn't implement a date type. If you are starting with a date/time and you know that your you are only dealing with a single timezone, AND you mean you want the current month in the curent year
$testdate=strtotime('2018-06-31 12:00'); // this will be converted to 2018-07-01
if (date('Ym')==date('Ym', $testdate)) {
// current month
} else {
// not current month
}

Compare difference between two dates PHP

I am trying to compare to date to figure out how much time is between them, which I know how to do, date_diff(), but I want to then compare the time between the dates and if it is greater than 7 days do something and if not do something else. I think it sounds easy and I know there are probably fairly simple solutions to do so but I am just not a fan of dates and comparisons. Here is a snippet of what I got so far as it is just one case of a switch statement so the rest are basically identical.
$array = array();
$today = date("Y-m-d"); // get today's date
foreach($arrayOfObjs as $obj){
if ($obj->get("renewalDate") >= $today){
array_push($array, $obj->get("renewalDate"));
}else{
switch($obj->get("recurrencePeriod")){
case 1:
/*
* All cases follow same structure
* Build the date in format Y-m-d from renewalDate out of the obj.
* Loop through the date while it's less than today.
* After date is greater than today return date add to array
*/
$date = DateTime::createFromFormat("Y-m-d", $obj->get('renewalDate'));
while($date <= $today){
$date->add(new DateInterval('P7D'));
}
$diff = date_diff($today, $date);
if($diff->format('%a') <= 7){
$obj->renewalDate($date);
array_push($array, $obj);
}
break;
Basically, my database stores dates and those dates could be passed but it could be a reoccurring event. To calculate the next time that event would happen I check if the data in the database is before today's date and if it is then I continue to add the incremental amount (in this case 7 for a weekly reoccurring event) and compare the dates again. After the date that is incremented passes today's date I want to find out if it is within 7 days and if so add it to an array to get returned. I know... since I'm adding 7and it's within 7 days the first reoccurring event will always be within 7 days but that is not the case for monthly events or anything greater.
All cases are broken so I only included this one for simplicity. I can get date_Diff to return something like 7 or 12 or whatever the number may be but how can I check if that number is within the 7 days I want?
Thanks, I will include more information if needed to clarify any misunderstandings.
I'm not entirely sure what you are trying to do, but how about the following if you are just projecting dates forward and backwards and want to know if they are 7 days or more either way:
$today = date("Y-m-d");
$todaytime = strtotime($today);
$testdate = "2017-06-31";
$testtime = strtotime($testdate);
$back7days = strtotime("-7 days",$todaytime);
if($testtime < $back7days)
echo "X"; // do somthing if testdate was more than 7 days ago
$fwd7days = strtotime("+7 days", $todaytime);
if($testtime > $fwd7days)
echo "Y"; // do somthing if testdate is more than 7 days in future
Just make sure that you use less-than or less-than-and-equals comparators etc to handle the boundary conditions you need.

Using the PHP date and time function to print a certain sentence

I'm in need of help with the PHP date/time function.
Using de date/time function, I need to print the following:
Today is 'current day', the 'number of day of month', in the year 'year'. Today is 'number of day of the year'. We still have 'number of days till end of year'.
Just can't get this working.. any ideas?
Thanks!
Alright so there may be a better way to do this, but this is one way of getting all the different elements you asked for:
$d = new DateTime();
$currentDay = $d->format('l'); // Will give you the current day in full (i.e. Monday)
$dayOfMonth = $d->format('j'); // Will give you the current day of the Month
$year = $d->format('Y'); // Will give you the current Year.
$dayOfYear = ($d->format('z') + 1); // Starts at 0, so we add one to get the actual days past.
As for the days left, I reckon there is potentially a better way to do this, but here's a quick solution:
$daysInYear = 365;
if ($d->format('L') === 1) { // Returns 1 if leap year.
$daysInYear = 366;
}
$daysLeft = $daysInYear - $dayOfYear;
That should give you all the variables you need to print out the statement you asked for.

How to find week number of a day in a month using php

hai i found this PHP get number of week for month quiet helpful but it makes some error on all months start on Sundays for example "2013-09-01" gives week number as 2 (actually its '1')..
any one got some idea?? please share thanks in advance.....
use date("W","2013-09-01");.it will return week number as 01.
Add strtotime function to it.. Works fine.. date("W",strtotime("2013-09-01"));
This utility function returns the week of the month for a specific day. Needs two args: the wanted day, and the first day of the same month
class WeekCalculator
{
public static function getWeekOfMonth($date, $firstDayOfMonth) {
$w1 = date("W", $firstDayOfMonth->getTimestamp());
$w2 = date("W", $date->getTimestamp());
$weekNum = $w2 - $w1 + 1;
return $weekNum;
}
}
Example usage
WeekCalculator::getWeekOfMonth(new \DateTime('2016-8-8'), new \DateTime('2016-8-1'));
Returns 2 (second week of August 2016)

Categories