PHP 7.1.7
There's a work function I'm dealing with that has a custom "week" (where a "week" for this function is Saturday through Friday).
For any given day of the week, how could I set two variables to contain the start of the custom defined week (Saturday) and the end of the custom defined week (Friday).
So, if I had a date of 8-11-17, I would need to come up with a a start date variable holding 8-05-17 and an end date variable holding 8-11-17.
Thanks
Not sure if I understood the question correct but is this what you are looking for?
It uses strtotime() to find previous saturday from input. Then next friday from that saturday.
$Input = "08/12/2017";
if(date("l", strtotime($Input)) == "Saturday"){
$Saturday = strtotime($Input);
}else{
$Saturday = strtotime($Input . " previous saturday");
}
$Friday = strtotime(date("m/d/Y", $Saturday) . " next friday");
echo date("m/d/Y", $Saturday) . " to " . date("m/d/Y", $Friday);
https://3v4l.org/l4g8D
EDIT; I just noticed if the Input is a saturday my code choosed the wrong dates. Corrected.
you could use date('w') to determine the day of week for given date.
If the number found is less than 6, move that number + 1 backwards. That's your starting date. End date will be 7 days later:
<?php
$date = new DateTime('08-11-2017');
$daynumber = $date->format('w');
if($daynumber < 6) {
$tomove = $daynumber + 1;
$date->modify('-' . $tomove.'day');
}
$startdate = $date;
$enddate = clone $date;
$enddate->modify('+7day');
echo $startdate->format('d-m-y');
echo $enddate->format('d-m-y');
?>
edit
forgot the word "day" in modify
Related
I'm trying to make stream events repeat weekly. I've written the code below which works but seems obtuse. Is there a better way to go about this?
A diagram of what I'd like to happen.
If the event date is in the past, update the event date to the nearest future day of the week that the event was originally on.
(I added the check to see if it was currently the same day as the original stream day because PHP's Stringtotime "This Tuesday" would jump to Tuesday of next week if today was Tuesday. Is there a better way around this?)
I'm relatively new to php so any help would be great!
// If a stream is set to weekly, and it's already over, this code updates its start and end times to the next day week day that it originally aired on.
if( ($weekly = true) && ($stream_end_epoch < $now) ){ //If Stream end date has past & repeat is turned on.
$stream_day_epoch = strtotime(get_post_meta( $stream_id, 'stream_day', true ));
$dayOfWeek = date("l", $stream_day_epoch);
$currentDate = new DateTime("now", new DateTimeZone($time_zone) );
$currentDay = $currentDate->format('l');
//Update the stream dates to the soonest week day they aired on.
if($dayOfWeek == $currentDay){
$stream_start_epoch = strtotime('Today '. $stream_start . $time_zone ); // update start (Set to yesterday because I'm getting a weird 1 day offset that I dont know where its coming from. this is super hackey and will probably break at certain times in the day, but i'm leaving it in this code until I can figure out a real solution.)
$stream_end_epoch = strtotime('Today '. $stream_end . $time_zone ); // update end.
}else{
$stream_start_epoch = strtotime('this '.$dayOfWeek. $stream_start . $time_zone ); // update start
$stream_end_epoch = strtotime('this '.$dayOfWeek. $stream_end . $time_zone ); // update end.
}
}
I think this could work for you:
$event_date = strtotime('2021-06-9');
$today = strtotime(date('Y-m-d'));
if($event_date < $today):
$dayOfWeek = date("l", $event_date);
$todayDay = date("l", $today);
$event_date = ($dayOfWeek !== $todayDay) ? strtotime("next " . $dayOfWeek) : $today;
endif;
var_dump(date('Y-m-d', $event_date));
if you set the event_date (for example) to 2021-06-04 (last Friday) the comparison will find that today is also Friday, so today is your next event day (and not on Friday of next week).
I have date in this form - - 20160428000000 (28th April 2016) i.e yyyymmdd...
I need that if some days(eg. 3) are added to this date - it should add them but not exceed the month(04) - expected output - 20160430000000 - 30th April
Similarly, 20160226000000 + 5days should return 20160229000000 i.e leap year Feb. That means, it should not jump to another month.
Any hints/Ideas ?
Another alternative would be to use DateTime classes to check it out:
First of course create your object thru the input. Then, set the ending day of the month object.
After that, make the addition then check if it exceeds the ending day. If yes, set it to the end, if not, then get the result of the addition:
$day = 5; // days to be added
$date = '20160226000000'; // input date
$dt = DateTime::createFromFormat('YmdHis', $date); // create the input date
$end = clone $dt; // clone / copy the input
$end->modify('last day of this month'); // and set it to last day
$dt->add(DateInterval::createFromDateString("+{$day} days")); // add x days
// make comparision
$final_date = ($dt > $end) ? $end->format('YmdHis') : $dt->format('YmdHis');
echo $final_date;
For this you can try like this:
$given_date = 20160428000000;
$no_of_day = 3;
if(date('m',strtotime($given_date)) < date('m',strtotime($given_date ." +".$no_of_day."days"))){
echo "Exceeded to next month <br/>";
echo "Last date of month should be: ".date("t M Y", strtotime($given_date));
}
else {
echo "Next date will be after ".$no_of_day." day(s)<br/>";
echo date('d M Y',strtotime($given_date ." +".$no_of_day."days"));
}
If month will jump to next month then it will show the current month last date.
other wise it will show date after number of days extended.
If the added date exceeds last day, will select the last day as the new date.
<?php
$date_orig = 20160226000000;
$add_day = 5; # No. of days to add
$added_date = strtotime($date_orig. ' + '.$add_day.' days'); // Add $add_day to $date_orig
$last_date = strtotime(date("YmtHis", strtotime($date_orig))); // Last day of $date_orig
$new_date = ($added_date > $last_date) ? $last_date : $added_date; // check the added date exceeds the last date
$new_date_format = date("YmdHis", $new_date); // Format Date
echo $new_date_format;
?>
<?php
$month_end = date('t-m-Y'); // Gets the last day of the month; e.g 31-07-2019
echo $month_end;
?>
I currently need to get the previous week from a variable that passes a php week number so if it is week 13 I will get week 12.
The problem I am facing is that if I just minus 1 from the original number if I am in week 1 it will return week 0 unless I create an if statement ie:
if($week==1)
{
$prev_week=52;
$prev_year=$year-1;
}
This is assuming that php counts the weeks from 1 and not 0. This seems a bit clumsy and I was thinking there may be a better way of doing this utilizing PHP's many date and time functions.
Try this:
$currentWeek = date( 'W' );
$today = strtotime( date( 'Y-m-d' ) ) - 7*24*60*60; // last week this day
// change 7 to 30 to see last year's week numer
$lastWeek = date( 'W', $today );
echo $currentWeek . '--' . $lastWeek;
Hope this helps.
Update
$lastWeekNumber = date( 'W', strtotime( 'last week' ) );
$PreviousWeek = date("W",strtotime("-1 week"));
HamZa's and web-nomad's answers helped me to go a bit further and make sure, I get the right year. Using date ('Y') can lead to unexpected behavior since it can happen, that week 1 belongs to the next or the previous year according to ISO-8601 (which is what is used in Europe). Instead use date ('o'). Otherwise it can happen that you jump from week 52 to week 1 of the previous year (because the start of the week is in the previous year according to date ('Y').
$jahr = 2014; // jahr means year
$kw = 52; // kw contains week
Using date ('Y')returns:
previousWeek: 51-2014
currentWeek: 52-2014
nextWeek: 01-2014
Using date ('o')returns:
previousWeek: 51-2014
currentWeek: 52-2014
nextWeek: 01-2015
See all the code together, e. g. for building forward and backward-links:
$kwBack['kw'] = date ("W", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' -1 week'));
$kwBack['jahr'] = date ("o", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' -1 week'));
$kwNext['kw'] = date ("W", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' +1 week'));
$kwNext['jahr'] = date ("o", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' +1 week'));
echo "previousWeek: " . $kwBack['kw'] . "-" . $kwBack['jahr'];
echo "<br>currentWeek: " . $kw . "-" . $jahr;
echo "<br>nextWeek: " . $kwNext['kw'] . "-" . $kwNext['jahr'];
echo "<br>";
// Build the links
$urlBack = $_SERVER['PHP_SELF'] . "?" . http_build_query ($kwBack);
$urlNext = $_SERVER['PHP_SELF'] . "?" . http_build_query ($kwNext);
echo "Previous week: ". $urlBack . "<br>";
echo "Next week: ". $urlNext;
I think I could be over complicating the problem - basically I need to obtain results from the database that appear in the previous weeks from the selected week therefore if there is a possibility of 54 weeks in a year all I really need to do is:-
if($week==1)
{
$year_minsued=$year-1;
$week_minused=54;
}
else
{
$week_minused=$week-1;
$year_minused=$year;
}
My select statement can then read:
SELECT SUM(post_price), SUM(total_price) FROM
database_table
WHERE client_id='$account_no'
AND
(year<='$year_minused' AND week<='$week_minused')
I have not tested this as yet but thinks it should do the job.
We know that a year can be between 52 or 53 weeks. So, I created here a function that receives the current week and the current year. If this is true, it is obvious that the previous week will be the last week of the previous year, so through the variable year that I gave to this function, I subtract 1 to have the value or the previous year and I try to know how many weeks this year has, in this case that will be the week before week 1 for example. Otherwise, I subtract 1 in the value of the current week to have the value of the previous week.
i hope i have helped
function PreviusWeekNumber($ActualWeek, $Year){
if($ActualWeek === 1){
$TransformYearIntolastYear = $Year -1;
$date = new DateTime;
$date->setISODate($TransformYearIntolastYear, 53);
$Result = ($date->format("W") === "53" ? 53 : 52);
}else{
$Result = $ActualWeek -1;
}
return $Result;
}
Check this
$year = 2013; // Retrieved from the DB
$week = 1;
$prev_week = date("W",strtotime($year. 'W'.str_pad($week, 2, 0, STR_PAD_LEFT). ' -1 week'));
echo $prev_week; // returns 52
A demo which shows the year:
$year = 2013; // Retrieved from the DB
$week = 1;
$prev_week = date("W - Y",strtotime($year. 'W'.str_pad($week, 2, 0, STR_PAD_LEFT). ' -1 week'));
echo $prev_week; // returns 52 - 2012
I am trying to get stripe to set a end_trial date on the next occurrence of whatever day of the month the user chooses. i.e. If today is the 16th and the user chooses the 15th I need the unix timestamp for the 15th of the next month. However if today was the 14th I need the timestamp for tomorrow.
I tried the solution found on this SO question Find the date for next 15th using php .
When i ran the code suggested in that question and substituted 15 for 31
$nextnth = mktime(0, 0, 0, date('n') + (date('j') >= 31), 31);
echo date('Y-m-d', $nextnth);
The result is 2013-03-03
I also tried this one Get the date of the next occurrence of the 18th .
The second one would actually give me 2013-03-31 when i ran it one 2013-1-31.
Both had unexpected results. Is february the problem? Any guidance will be much appreciated.
Here is a way to do it.
function nextDate($userDay){
$today = date('d'); // today
$target = date('Y-m-'.$userDay); // target day
if($today <= $userDay){
$return = strtotime($target);
}
else{
$thisMonth = date('m') + 1;
$thisYear = date('Y');
if($userDay >= 28 && $thisMonth == 2){
$userDay = 28;
}
while(!checkdate($thisMonth,$userDay,$thisYear)){
$thisMonth++;
if($thisMonth == 13){
$thisMonth = 1;
$thisYear++;
}
}
$return = strtotime($thisYear.'-'.$thisMonth.'-'.$userDay);
}
return $return;
}
// usage
echo date('Y-m-d',nextDate(29));
We get the user's choice and compare it today.
If today is less than or equal to user choice, we return the timestamp for this month.
If today is greater than user choice, we loop through dates, adding a month (or a year if it's $thisMonth hits 13). Once this date does exist again, we have our answer.
We check the dates using php's checkdate function, strtotime and date.
I really don't understand the question completely. You can easily determine the date for next 30 days for example
$next_ts = time() + 30 * 86400; // add 30 days to current timestamp
$next = date('Y-m-d', $next_ts); // format string as Y-m-d
echo $next;
If that is not what you need, please explain the problem.
I would like to be able to find the date which "Sunday" falls on for a given date, formatted as YYYY-MM-DD.
... How would this be achieved in PHP?
strtotime() may help you, it accepts GNU-Date-input-formats like "next Sunday"
echo date('Y-m-d',strtotime('sunday',strtotime("2011-07-04 Z")));
Look at the time function for php.
If you can't find a library that does this, then:
Come up with a reference date (January 1, 1970?) for which you know the day of the week.
Calculate the number of days between the reference date and your given date.
Take that answer modulo 7.
Convert to a day of the week.
Here you have a full example with multiples values
it is for PHP or any other lenguage that uses epoch time (or similar)
<?php
function prevSunday($paramDay){
$aDay = 24*60*60;
$aWeek = $aDay * 7;
$sunday = $aDay + $paramDay - (($paramDay - 3 * $aDay) % $aWeek);
return $sunday;
}
$randDay = 1309819423 + rand(0, 9000000); // this contanis a random day (and hours, minutes, seconds)
$aSaterday = strtotime("20110702");
$aSunday = strtotime("20110703");
$aMonday = strtotime("20110704");
echoTwoDays($aSuterday, prevSunday($aSuterday));
echoTwoDays($aSunday, prevSunday($aSunday));
echoTwoDays($aMonday, prevSunday($aMonday));
/* echoes
day1: Saturday 20110702
day2: Sunday 20110626
day1: Sunday 20110703
day2: Sunday 20110703
day1: Monday 20110704
day2: Sunday 20110703
*/
echoTwoDays($randDay, prevSunday($randDay)); // echoes a random date and perv sunday
function echoTwoDays ($day1, $day2) {
echo "day1: " . date("l Ymd", $day1) ."<br>"; // remove l as your request
echo "day2: " . date("l Ymd", $day2) ."<br><br>"; // remove l as your request
}
function prevSunday($paramDay){
$aDay = 24*60*60;
$aWeek = $aDay * 7;
$sunday = $aDay + $paramDay - (($paramDay - 3 * $aDay) % $aWeek);
return $sunday;
}
?>