determine week when pick a day - php

I'm trying to accomplish the following task. I'm developing a custom calendar with three views (day,week and month), there may be something out there already but I'm rewriting this as part of learning tool for me as well.
So user will face with Day view when they first visit, with arrows to go back and forth to next day or previous day of course. If they click on Week View, it will give them a 7 days overview with today date as default, and once again they can go back and forth to next week or previous week. The last view is the full month calendar, once they click on the day, it will give them the detail of the day and at the same time reset the default as the day they pick. So if they go back to week view, they will see the detail for the week contain the day that they picked. This is where I have trouble wrapping my head around with, I know there are PHP functions that determine the day of the week but I can't seem to think about how to pass in the date and get the full week starting from Sunday for the day that passed in. For example, if I passed in 10/12/2012, I'd like to start the week at 10/07/12 - 10/13/12.
Thank you kindly for your help or pointing to the right direction. Please excuse my grammar/spelling mistakes as well.

Assuming that $selection represents the user's selected date as an
integer timestamp, date('N', $selection) will return a numeric
representation of day of the week of their selection (e.g. Monday =
1 through Sunday = 7).
This result also represents the number of days since the start of
the selected week (the previous Sunday) - $offset. Of course, if
you're beginning with a string representation of the users selected
date (as in your question, 10/12/2012), you would first need to
convert the date to an integer timestamp.
$selection = strtotime($selection); //if $selection is in string format
$offset = date('N', $selection);
Now you may use $offset to establish date of the the start of the
week (the previous Sunday) - $weekstart.
$weekstart = strtotime("$selection -$offset day");
Once you've got the start of the week, the end of the week
($weekend) is, of course, 6 days later, but to calculate this
date, you first need to convert $weekstart from an integer
timestamp into a string representation of the date. You'll also need to convert the result ($weekend) into a string representation of the date.
$weekstart = stringftime("%m/%d/%Y", $weekstart); //date format = 10/07/2012
$weekend = strtotime("$weekstart +6 day");
$weekend = stringftime("%m/%d/%Y", $weekend);
So the following:
$selection = "10/12/2012";
$selection = strtotime($selection);
$offset = date('N', $selection);
$weekstart = strtotime("$selection -$offset day");
$weekstart = stringftime("%m/%d/%Y", $weekstart);
$weekend = strtotime("$weekstart +6 day");
$weekend = stringftime("%m/%d/%Y", $weekend);
$output = "Selected Date = $selection \n Selected Week = $weekstart - $weekend";
echo $output;
results in:
Selected Date = 10/12/2012
Selected Week = 10/07/2012 - 10/13/2020
See:
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/function.strftime.php

use strtotime() function coupled with date() function for this task
for eg. 1 day before 2012-10-09 is
echo date('Y-m-d', strtotime("2012-10-09 -1 day"));

Building on Wisdom's answer, you can find the 1st day of the week in a couple steps. Check out the PHP date() manual for more options, but I believe the following code will work:
// figure out how many days back you have to go, to get to Sunday
$d = date('N', strtotime($mydate));
// figure out Sunday's date
$beginning_of_week = date('Y-m-d', strtotime($mydate." -{$d} days"));
$end_of_week = date('Y-m-d', strtotime($beginning_of_week." +1 week"));
echo "The week {$beginning_of_week} to {$end_of_week}! ";

Try this function (source: Marty Wallace).
The date you are interested in is $date (in YYYY-MM-DD format), and $rollover in full day format (e.g. Friday).
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$i = 1;
$weeks = 1;
for($i; $i<=$elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover)) $weeks ++;
}
return $weeks;
}

Related

Get previous month value in PHP

I have used the below PHP function to get the previous month,
$currmonth = date('m', strtotime('-1 month'));
It was working fine and I was getting the value of 04 till yesterday. On today May 31st (Last day of the month May), I noticed the function returns the current month only. That is 05. Is there any other alternate function which returns the previous month accurately.
Try strtotime("first day of last month").
The first day of is the important part as detailed here.
Literally ask strtotime for the 'first day of the previous month' this makes sure it selects the correct month:-
$currmonth = date("m", strtotime("first day of previous month"));
You can use OOP with DateTime class and modify method:
$now = new DateTime();
$previousMonth = $now->modify('first day of previous month');
echo $previousMonth->format('m');
strtotime() works accurately. The problem is what you ask it to return.
"-1 month" is not the same as "previous month". It is the same as "subtract 1 from current month then normalize the result".
On 2017-05-31, subtracting 1 from current month gets 2017-04-31 which is not a valid date. After normalization, it becomes 2017-05-01, hence the result you get.
There are more than one way to get the value you need. For example:
// Today
$now = new DateTime('now');
// Create a date interval string to go back to the first day of the previous month
$int = sprintf('P1M%dD', $now->format('j')-1);
// Get the first day of the previous month as DateTime
$fdopm = $now->sub(new DateInterval($int));
// Verify it works
echo($fdopm->format('Y-m-d'));
// On 2017-05-31 it should print:
// 2017-04-01
If you just need to get the month number of previous month, the following should suffice.
$m = idate("m") - 1;
// wrap to previous year
if ($m < 1) {
$m = 12 - abs($m) % 12;
}
This works with arbitrary number of subtracted months.

How to set the "first day of the week" to Thursday in PHP

I want to set the first day of the week to Thursday (not Sunday or Monday), because it's the company's cut-off date.
I already have a code to determine the current week number of a date but it starts in Sunday or Monday.
How to modify these to my preference?
function findweek($date) {
$monthstart=date("N",strtotime(date("n/l/Y",strtotime($date))));
$newdate=(date("j",strtotime($date))+$monthstart)/7;
$ddate=floor($newdate);
if($ddate != $date) {
$ddate++;
}
return $ddate;
}
http://php.net/manual/en/datetime.formats.relative.php says that as of PHP version 5.6.23, 7.0.8 "Weeks always start on monday. Formerly, sunday would also be considered to start a week." That said, is your problem that the number of weeks returned might be incorrect depending on whether today falls on or before Thursday of the current week? Maybe try something like this:
$date = new DateTime();
$week = intval($date->format('W'));
$day = intval($date->format('N'));
echo $day < 4 ? $week-1 : $week;
If subtracting 1 isn't the answer you could play around with addition/subtraction, comparing the result with the actual answer you know to be true until you get the right formula. Hope this helps!
This should work.
function findweek($date, $type = "l") {
$time = strtotime($date);
return date($type, mktime(0, 0, 0, date("m", $time) , date("d", $time)-date("d", $time)+1, date("Y", $time)));
}
echo findweek('2015-09-16');

How to calculate the number of business days between two dates in PHP?

I have a situation like this. I have a string stored in DB, like this:
$string: 1,1,1,1,1,1,0
It means: Sunday is 0 (a holiday), all the other days (Mon...Sat) are 1.
Then I have two dates: today (ex: 2012-09-07) and some end date (2012-10-04).
I wonder what should I do to get the total number of business days (deducting the holidays) between Today and this End Date (23 days in my example)? We should use the string stored in the DB.
$workdays = explode(",", "1,1,1,1,1,1,0"); // turn string to array (Monday to Sunday)
$days = 0;
$time = strtotime("2012-09-07");
$end_time = strtotime("2012-10-04");
while ($time < $end_time)
{
$day_of_week = date("N", $time) - 1; // 0 = Monday, 6 = Sunday
if ($workdays[$day_of_week] == 1)
{
$days++;
}
$time = strtotime("+1 day", $time); // add one day to time
}
This should work for you. You may need to modify it based on whether it's inclusive, when it should start, etc.
Have you tried date_diff() ?
http://php.net/manual/en/function.date-diff.php

How to get previous month and year relative to today, using strtotime and date?

I need to get previous month and year, relative to current date.
However, see following example.
// Today is 2011-03-30
echo date('Y-m-d', strtotime('last month'));
// Output:
2011-03-02
This behavior is understandable (to a certain point), due to different number of days in february and march, and code in example above is what I need, but works only 100% correctly for between 1st and 28th of each month.
So, how to get last month AND year (think of date("Y-m")) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on strtotime argument parsing.
Update. To clarify requirements a bit.
I have a piece of code that gets some statistics of last couple of months, but I first show stats from last month, and then load other months when needed. That's intended purpose. So, during THIS month, I want to find out which month-year should I pull in order to load PREVIOUS month stats.
I also have a code that is timezone-aware (not really important right now), and that accepts strtotime-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using strtotime-compatible strings.
I know it can be done with few conditionals and basic math, but that's really messy, compared to this, for example (if it worked correctly, of course):
echo tz::date('last month')->format('Y-d')
So, I ONLY need previous month and year, in a strtotime-compatible fashion.
Answer (thanks, #dnagirl):
// Today is 2011-03-30
echo date('Y-m-d', strtotime('first day of last month')); // Output: 2011-02-01
Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:
$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02
if the day itself doesn't matter do this:
echo date('Y-m-d', strtotime(date('Y-m')." -1 month"));
I found an answer as I had the same issue today which is a 31st. It's not a bug in php as some would suggest, but is the expected functionality (in some since). According to this post what strtotime actually does is set the month back by one and does not modify the number of days. So in the event of today, May 31st, it's looking for April-31st which is an invalid date. So it then takes April 30 an then adds 1 day past it and yields May 1st.
In your example 2011-03-30, it would go back one month to February 30th, which is invalid since February only has 28 days. It then takes difference of those days (30-28 = 2) and then moves two days past February 28th which is March 2nd.
As others have pointed out, the best way to get "last month" is to add in either "first day of" or "last day of" using either strtotime or the DateTime object:
// Today being 2012-05-31
//All the following return 2012-04-30
echo date('Y-m-d', strtotime("last day of -1 month"));
echo date('Y-m-d', strtotime("last day of last month"));
echo date_create("last day of -1 month")->format('Y-m-d');
// All the following return 2012-04-01
echo date('Y-m-d', strtotime("first day of -1 month"));
echo date('Y-m-d', strtotime("first day of last month"));
echo date_create("first day of -1 month")->format('Y-m-d');
So using these it's possible to create a date range if your making a query etc.
If you want the previous year and month relative to a specific date and have DateTime available then you can do this:
$d = new \DateTimeImmutable('2013-01-01', new \DateTimeZone('UTC'));
$firstDay = $d->modify('first day of previous month');
$year = $firstDay->format('Y'); //2012
$month = $firstDay->format('m'); //12
date('Y-m', strtotime('first day of last month'));
strtotime have second timestamp parameter that make the first parameter relative to second parameter. So you can do this:
date('Y-m', strtotime('-1 month', time()))
if i understand the question correctly you just want last month and the year it is in:
<?php
$month = date('m');
$year = date('Y');
$last_month = $month-1%12;
echo ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month);
?>
Here is the example: http://codepad.org/c99nVKG8
ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.
$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));
I think you've found a bug in the strtotime function. Whenever I have to work around this, I always find myself doing math on the month/year values. Try something like this:
$LastMonth = (date('n') - 1) % 12;
$Year = date('Y') - !$LastMonth;
date("m-Y", strtotime("-1 months"));
would solve this
Perhaps slightly more long winded than you want, but i've used more code than maybe nescessary in order for it to be more readable.
That said, it comes out with the same result as you are getting - what is it you want/expect it to come out with?
//Today is whenever I want it to be.
$today = mktime(0,0,0,3,31,2011);
$hour = date("H",$today);
$minute = date("i",$today);
$second = date("s",$today);
$month = date("m",$today);
$day = date("d",$today);
$year = date("Y",$today);
echo "Today: ".date('Y-m-d', $today)."<br/>";
echo "Recalulated: ".date("Y-m-d",mktime($hour,$minute,$second,$month-1,$day,$year));
If you just want the month and year, then just set the day to be '01' rather than taking 'todays' day:
$day = 1;
That should give you what you need. You can just set the hour, minute and second to zero as well as you aren't interested in using those.
date("Y-m",mktime(0,0,0,$month-1,1,$year);
Cuts it down quite a bit ;-)
This is because the previous month has less days than the current month. I've fixed this by first checking if the previous month has less days that the current and changing the calculation based on it.
If it has less days get the last day of -1 month else get the current day -1 month:
if (date('d') > date('d', strtotime('last day of -1 month')))
{
$first_end = date('Y-m-d', strtotime('last day of -1 month'));
}
else
{
$first_end = date('Y-m-d', strtotime('-1 month'));
}
If a DateTime solution is acceptable this snippet returns the year of last month and month of last month avoiding the possible trap when you run this in January.
function fn_LastMonthYearNumber()
{
$now = new DateTime();
$lastMonth = $now->sub(new DateInterval('P1M'));
$lm= $lastMonth->format('m');
$ly= $lastMonth->format('Y');
return array($lm,$ly);
}
//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
if($beforeMonth !="" && $beforeMonth >= 1) {
$date = date('Y')."-".date('m')."-15";
$timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
return $timestamp_before;
} else {
$time= time();
return $time;
}
}
//call function
$month_year = date("Y-m",getMonthYear(1));// last month before current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month
function getOnemonthBefore($date){
$day = intval(date("t", strtotime("$date")));//get the last day of the month
$month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
return $month_date;
}
The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.
NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.

Getting the date for current day in PHP

I want to get the date for current day in php. what i tried is here...
echo $x."<br>";
echo date("D",$x)."<br>";
But the output was
21-02-10
Thu
It is giving correct date but not the correct day value.Why..?
What I want day is the date for monday for the current week which can be generated on any day of the week. so what I did was, I'm taking the today's day and comparing with (Mon,Tue.... Sun) and respectively creating a timestamp using
case "Mon":
$startdate1=date("d-m-y");
$parts = explode('-',$startdate1);
$startdate2 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+1),$parts[2]));
$startdate3 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+2),$parts[2]));
$startdate4 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+3),$parts[2]));
$startdate5 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+4),$parts[2]));
$startdate6 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+5),$parts[2]));
$startdate7 = date('d-m-Y',mktime(0,0,0,$parts[1],($parts[0]+6),$parts[2]));
$dates=array(1 => $startdate1,$startdate2,$startdate3,$startdate4,$startdate5,$startdate6,$startdate7);
$i=1;
while( $i <= 7 )
{
echo $dates[$i];
$i++;
}
break;
$date is the final array respective to today that has to be returned. Is there any other better method to do this operation.
I tried this to get current day.
echo date('l'); // output: current day.
How about this:
//today is monday
if (1 == date('N')){
$monday = time();
}else{
$monday = strtotime('last Monday');
}
for ($i = 0; $i < 7; $i++){
echo date('d-m-Y', $monday) . '<br>';
$monday = strtotime('tomorrow', $monday);
}
First find Monday, if it is not today, then print 7 dates
What I want day is the date for monday
for the current week which can be
generated on any day of the week.
That's what you want. $mday is the month day of this week's Monday. Nevermind if it's not positive, mktime will handle that right. $monday has the timestamp of the Monday's midnight.
$now = getdate();
$mday = $now['mday'] - ($now['wday'] + 6) % 7;
$monday = mktime(0, 0, 0, $now['mon'], $mday, $now['year']);
echo(date('d-m-y', $monday));
What i did to resolve it is used the date format ('d-m-Y') instead of ('d-m-y') in date function, which was causing the problem. Hence strtotime accepted the format and gave the correct result for
$t=date('d-m-Y');
echo date("D",strtotime($t));
I use the function date and path to it the "D" that refere to the current day , and it works with me
$today = date("D");
and to get the full info about the current date
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
what i tried is here...
echo date("D",$x)."<br>";
date expects a timestamp (int) value as the second parameter. Your $x is a string containing an ambiguous date format. Convert that date into a timestamp first, using strptime or strtotime and use the date function correctly to get the correct day value.
Regarding your second part, you don't need to (and shouldn't) check the day name to calculate the correct Monday, Tuesday etc. A more efficient approach is for example using strtotime to get last Monday etc.
You are likely passing a string as timestamp
echo $x."<br>";
echo date("D",$x)."<br>";
Remove $x and it will output the correct day or change it to
$x = '21-02-2010';
echo date('D', strtotime($x));

Categories