php - Get array of dates in same week as a $date [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Sorry for my bad english.
As said in the title , i would to get array of dates in same week(between monday to friday) as a $date
exemple : if $date = 2015-05-05 => i would to have
array that contain : 2015-05-04 , 2015-05-05 ,2015-05-06 2015-05-07, 2015-05-08

Just change the date strings of "2015-05-05" to your desired date.
$day_of_week = date('N', strtotime('2015-05-05'));
$given_date = strtotime("05-05-2015");
$first_of_week = date('Y-m-d', strtotime("- {$day_of_week} day", $given_date));
$first_of_week = strtotime($first_of_week);
for($i=0 ;$i<=7; $i++) {
$week_array[] = date('Y-m-d', strtotime("+ {$i} day", $first_of_week));
}
print_r($week_array);

Date and strtotime are your friends on this:
$myDate = "2015-05-05";
echo date("Y-m-d", strtotime('monday this week', strtotime($myDate)))."\n";
echo date("Y-m-d", strtotime('tuesday this week', strtotime($myDate)))."\n";
echo date("Y-m-d", strtotime('wednesday this week', strtotime($myDate)))."\n";
echo date("Y-m-d", strtotime('thursday this week', strtotime($myDate)))."\n";
echo date("Y-m-d", strtotime('friday this week', strtotime($myDate)))."\n";
Output:
2015-04-05
2015-05-05
2015-06-05
2015-07-05
2015-08-05
Demo:
http://ideone.com/hEem8k

Yet another solution
$my_date = "2012-10-18";
$week = date("W", strtotime($my_date)); // get week
$y = date("Y", strtotime($my_date)); // get year
echo $first_date = date('d-m-Y',strtotime($y."W".$week)); //first date
echo $second_date = date("d-m-Y",strtotime("+1 day", strtotime($first_date)));
you can loop or add +1 to previous date and so on..

This function will return all dates of current week starting from monday to sunday
See Working Demo
function GetCurrentWeekDates()
{
if (date('D') != 'Mon') {
$startdate = date('Y-m-d', strtotime('last Monday'));
} else {
$startdate = date('Y-m-d');
}
//always next saturday
if (date('D') != 'Sat') {
$enddate = date('Y-m-d', strtotime('next Saturday'));
} else {
$enddate = date('Y-m-d');
}
$DateArray = array();
$timestamp = strtotime($startdate);
while ($startdate <= $enddate) {
$startdate = date('Y-m-d', $timestamp);
$DateArray[] = $startdate;
$timestamp = strtotime('+1 days', strtotime($startdate));
}
return $DateArray;
}
print_r(GetCurrentWeekDates());

Related

PHP subtract 1 month from date formatted with date ('m-Y')

I'm trying to subtract 1 month from a date.
$today = date('m-Y');
This gives: 08-2016
How can I subtract a month to get 07-2016?
<?php
echo $newdate = date("m-Y", strtotime("-1 months"));
output
07-2016
Warning! The above-mentioned examples won't work if call them at the end of a month.
<?php
$now = mktime(0, 0, 0, 10, 31, 2017);
echo date("m-Y", $now)."\n";
echo date("m-Y", strtotime("-1 months", $now))."\n";
will output:
10-2017
10-2017
The following example will produce the same result:
$date = new DateTime('2017-10-31 00:00:00');
echo $date->format('m-Y')."\n";
$date->modify('-1 month');
echo $date->format('m-Y')."\n";
Plenty of ways how to solve the issue can be found in another thread: PHP DateTime::modify adding and subtracting months
Try this,
$today = date('m-Y');
$newdate = date('m-Y', strtotime('-1 months', strtotime($today)));
echo $newdate;
Depending on your PHP version you can use DateTime object (introduced in PHP 5.2 if I remember correctly):
<?php
$today = new DateTime(); // This will create a DateTime object with the current date
$today->modify('-1 month');
You can pass another date to the constructor, it does not have to be the current date. More information: http://php.net/manual/en/datetime.modify.php
I used this to prevent the "last days of month"-error. I just use a second strtotime() to set the date to the first day of the month:
<?php
echo $newdate = date("m-Y", strtotime("-1 months", strtotime(date("Y-m")."-01")));
if(date("d") > 28){
$date = date("Y-m", strtotime("-".$loop." months -2 Day"));
} else {
$date = date("Y-m", strtotime("-".$loop." months"));
}
$lastMonth = date('Y-m', strtotime('-1 MONTH'));
First change the date format m-Y to Y-m
$date = $_POST('date'); // Post month
or
$date = date('m-Y'); // currrent month
$date_txt = date_create_from_format('m-Y', $date);
$change_format = date_format($date_txt, 'Y-m');
This code minus 1 month to the given date
$final_date = new DateTime($change_format);
$final_date->modify('-1 month');
$output = $final_date->format('m-Y');
Try this,
$effectiveDate = date('2018-01'); <br>
echo 'Date'.$effectiveDate;<br>
$effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));<br>
echo 'Date'.$effectiveDate;
$currentMonth = date('m', time());
$currentDay = date('d',time());
$currentYear = date('Y',time());
$lastMonth = $currentMonth -1;
$one_month_ago=mkdate(0,0,0,$one_month_ago,$currentDay,$currentYear);
This could be rewritten more elegantly, but it works for me
I realize this is an old post, but I've been solving the same issue, and here is what I came up with to account for all the variability. This function is just trying to get relative dates, so same day of prior month, or last day of month if you are on the last day, regardless of exactly how many days a month has. So goal is given '2010-03-31' and subtract a month, we should output '2010-02-28'.
private function subtractRelativeMonth(DateTime $incomingDate): DateTime
{
$year = $incomingDate->format('Y');
$month = $incomingDate->format('m');
$day = $incomingDate->format('d');
$daysInOldMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
if ($month == 1) { //It's January, so we have to go back to December of prior year
$month = 12;
$year--;
} else {
$month--;
}
$daysInNewMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
if ($day > $daysInNewMonth && $month == 2) { //New month is Feb
$day = $daysInNewMonth;
}
if ($day > 29 && $daysInOldMonth > $daysInNewMonth) {
$day = $daysInNewMonth;
}
$adjustedDate = new \DateTime($year . '-' . $month . '-' . $day);
return $adjustedDate;
}

PHP get a date one month later [duplicate]

This question already has answers here:
How to get the previous and next month?
(8 answers)
Closed 8 years ago.
<?php
echo "\n";
echo $end_date = date('Y-m-d', strtotime('+1 month'));
echo "\n";
$today = date("Y-m-d"); // 2012-01-30
echo $next_month = date("Y-m-d", strtotime("$today +1 month"));
echo "\n";
$end_date = mktime(date("H"), date("i"), date("s"), date("n") + 1, date("j"), date("Y"));
echo "\n" . date('Y-m-d',$end_date);
http://codepad.org/bHiNFIBR
How can I get the correct date +1 months
I tried these options.
all returned 1 May but I need April 30
Try something like that..
if( date('d') == 31 || (date('m') == 1 && date('d') > 28)){
$date = strtotime('last day of next month');
} else {
$date = strtotime('+1 months');
}
echo date('Y-m-d', $date);
But just note that when you are 31st March as +1month its correct to target 1st of May not 30th April :)
I'd suggest this:
$next_month = date('Y-m-d', strtotime("+1 months", strtotime("NOW")));
EDIT
function addMonth($date) {
$date = new DateTime($date);
$day = $date->format('j');
$date->modify("+1 month");
$next_month_day = $date->format('j');
if ($day != $next_month_day)
$date->modify('last day of last month');
return $date;
}
$next_month = addMonth(time());
echo $next_month->format("Y-m-d");
hope this helps :-)
Try this solution:
echo "\n";
$today = date("Y-m-d");
$next_month = date("Y-m-d", strtotime("$today +1 month"));
echo "\n";
echo $next_month_last_day = date("Y-m-d",strtotime('-1 second',strtotime($next_month)));

How to find get week duration or week range from sunday to friday in php

How to find get week duration or week range from monday to friday for the given date in php.
for example i have date
$date = "2013-02-24";
Now i want range of date from monday to friday for the month
Just Try Out this answer.
$date = "2013-02-24";
$week = date('W', strtotime($date));
$year = date('o', strtotime($date));
echo "first day of week". $from = date("Y-m-d", strtotime("{$year}-W{$week}-1"));
echo "end day of week". $to = date("Y-m-d", strtotime("{$year}-W{$week}-5"));
function week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last monday', $ts);
return array(date('Y-m-d', $start),
date('Y-m-d', strtotime('next friday', $start)));
}
And call it like this:
list($start_date, $end_date) = week_range('2009-05-10');

Dates in php Sunday and Saturday?

i have one date.
example : $date='2011-21-12';
data format :yyyy-dd-mm;
IF date is Saturday or Sunday.
if Saturday add 2 day to the given date.
if Sunday add 1 day to the given date.
?
In a single line of code:
if (date('N', $date) > 5) $nextweekday = date('Y-m-d', strtotime("next Monday", $date));
If the day of week has a value greater than 5 (Monday = 1, Sat is 6 and Sun is 7) set $nextweekday to the YYYY-MM-DD value of the following Monday.
Editing to add, because the date format may not be accepted, you would need to reformat the date first. Add the following lines above my code:
$pieces = explode('-', $date);
$date = $pieces[0].'-'.$pieces[2].'-'.$pieces[1];
This will put the date in Y-m-d order so that strtotime can recognize it.
You can use the date and strtotime functions for this, like so:
$date = strtotime('2011-12-21');
$is_saturday = date('l', $date) == 'Saturday';
$is_sunday = date('l', $date) == 'Sunday';
if($is_saturday) {
$date = strtotime('+2 days', $date);
} else if($is_sunday) {
$date = strtotime('+1 days', $date);
}
echo 'Date is now ' . date('Y-m-d H:i:s', $date);
What about this:
$date='2011-21-12';
if (date("D", strtotime($date)) == "Sat"){
$new_date = date("Y-m-d", strtotime("+ 2 days",$date);
}
else if (date("D", strtotime($date)) == "Sun"){
$new_date = date("Y-m-d", strtotime("+ 1 day",$date);
}
The DateTime object can be really helpful for anything like this.
In this case.
$date = DateTime::createFromFormat('Y-d-m', '2011-21-12');
if ($date->format('l') == 'Sunday')
$date->modify('+1 day');
elseif ($date->format('l') == 'Saturday')
$date->modify('+2 days');
If you want to get the date back in that format.
$date = $date->format('Y-d-m');
$date = '2011-21-12'
$stamp = strtotime($date);
$day = date("l", $stamp);
if ($day == "Saturday"){
$stamp = $stamp + (2*+86400);
}elseif($day == "Sunday"){
$stamp = $stamp + 86400;
}
echo date("Y-d-m", $stamp);
The only reason i can think why this wouldnt work is strtotime not recognising that data format...
For sundays date('w',$date) will return 0, so the simplest test code is:
if(!date('w',strtotime($date)) { ... } //sunday
I just subtracted the difference from 8 an added it to the days.
if(date('N', strtotime($date)) >= 6) {
$n = (8 - date("N",strtotime($date)));
$date = date("Y-m-d", strtotime("+".$n." days");
}

how to get the previous 3 months in php

how to get the previous 3 months in php ex(If i say DEC.. It should display the previous 3 months i.e., OCT NOV DEC)
You can use the strtotime function like this:
echo date('M', strtotime('-3 month'));
So you specify previous dates with minus sign.
echo date('M', strtotime('0 month'));
echo date('M', strtotime('-1 month'));
echo date('M', strtotime('-2 month'));
echo date('M', strtotime('-3 month'));
Results:
Dec
Nov
Oct
Sep
You can do the same if you are using a loop like this:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month"));
}
Results:
Sep
Oct
Nov
Dec
Check out the documentation too see many other friendly date and time keywords strtotime supports:
http://php.net/manual/en/function.strtotime.php
Voted answer is almost correct.
Correct solution is:
for ($i = -3; $i <= 0; $i++){
echo date('M', strtotime("$i month", strtotime(date("Y-m-15"))));
}
Explain: strtotime default implementation is:
date ( string $format [, int $timestamp = time() ] ) : string
As you can see there is timestamp with default value of: time().
Last say today is 31th March.
Because there is no 31th Feb
echo date('M', strtotime("-1 month"));
will return March
On the other hand:
echo date('M', strtotime("+1 month"));
will return May (April will be skipped).
Because of that issue we have to setup timestamp value which is a safe date.
Every date between 1-28 is safe because every month have got that date. In my example I had choose 15th day of month.
$month = date('M');
$year = date('Y');
$no_of_mnths = date('n',strtotime("-2 months"));
$remaining_months = (12 - $no_of_mnths)."\r\n";
$tot = $remaining_months+1;
for($j=0;$j<$tot;$j++){
echo date('M',strtotime(''.$no_of_mnths.' months'))
$no_of_mnths++;
}
This may help you`
<?php
$date = explode("-", "2016-08-31");
if($date[2]== "01"){$days = "-0 days";}else{$days = "-1 days";}
$time = strtotime($days, mktime(0, 0, 0, $date[1], $date[2], $date[0]));
$MTD = date('Y-m-01', strtotime('0 month'));
$M1 = date('Y-m-01', strtotime('-1 month'));
$M2 = date('Y-m-01', strtotime('-2 month'));
$M3 = date('Y-m-01', strtotime('-3 month'));
$rng = array();
$rng[$MTD] = strftime("%B, %Y", strtotime(" ", $time));
$rng[$M1] = strftime("%B, %Y", strtotime("first day of previous month", $time));
$rng[$M2] = strftime("%B, %Y", strtotime("-2 months", $time));
$rng[$M3] = strftime("%B, %Y", strtotime("-3 months", $time));
?>
Here $MTD ,$M1,$M2,$M3 will give date in the form of "dd-mm-yyyy" and $rng[$MTD], $rng[$M1],$rng[$M2],$rng[$M3] give date in the form of"Name of Month,year" => (i.e August,2016)

Categories