How to get third previous month from inputted month-year? - php

I am trying to get third previous month from inputted month-year ie. if I give 06-2016 as an input, it should give me 03-2016 as result. I have tried strtotime("-3 Months"). But it gives me just 3 months from current date time.
Can someone tell me how to solve it please.
I have tried:
$month = 06;
$year = 2016;
$d = mktime(0, 0, 0, $month, 1, $year);
$td = date("Y-m-d", $d);
$oldDate = date('Y-m-d', strtotime("-3 Months"));
It gives me 3 months from current date. Any guesses how do I get the expected result ?

Use below. You need to use date("F Y", strtotime( INPUT_DATE ." -3 months"))
$month = 06;
$year = 2016;
$d = mktime(0, 0, 0, $month, 1, $year);
$td = date("Y-m-d", $d);
echo $olddate = date("Y-m-d", strtotime( $td ." -3 months"));
echo $months = date("F Y", strtotime( $td ." -3 months"));
Output:
2016-03-01
March 2016
Online Demo: Click Here

strtotime of (Input Date ."-3 Months")
$month = 06;
$year = 2016;
$d = mktime(0, 0, 0, $month, 1, $year);
$td = date("Y-m-d", $d);
$oldDate = date('Y-m-d', strtotime($td."-3 Months"));
$oldDate_MonthYear = date('m-Y', strtotime($td."-3 Months"));
echo $oldDate;
echo '<br />';
echo $oldDate_MonthYear;

Use Object Based.
$date1 = new DateTime("2016-06-01");
echo $startDate = $date1->modify("-3 month")->format('Y-m-d');

Try this and you should get desired result.
$prev_month_ts = strtotime('2016-06 -3 month');
$prev_month = date('Y-m', $prev_month_ts);
echo $prev_month;

Related

foreach loop does not go past start of range

I am trying to build a loop that echoes each month of the year until the current month. My foreach loop just stays on the start and doesn't progress through the rest of the range. Here is my code:
$startMonth = '01';
$endMonth = date('m');
foreach (range($startMonth, $endMonth) as $month) {
$dataValue = date('n', $month);
echo '<td class="month" data-value="';
echo $dataValue;
echo '" data-id="' . $incrementYear . '"><a href="/Archive/view/';
echo $incrementYear;
echo '/';
echo date('m', $month);
echo '">';
echo date('F', $month);
echo '</a></td>';
}
Here is the output:
January January January January January January
Each of the months has the correct link for what January should have, but for some reason, the range never leaves "01" which is the $startMonth and I'm not sure why. I was thinking it had something to do with integer vs. string, but removing the ' from $startMonth = '01'; to make it an integer, but that didn't work either.
As far as I understand them, I am using the range correctly.
What am I missing here?
EDIT
$dataValue can be commented out and I will still get January 6 times, its just the link will have a data-value different than what I want. This variable has no effect on the month itself.
If I change the bottom line of code from echo date('F', $month); to echo $month; I get:
1 2 3 4 5 6
Problem is that to date() as timestamp you always pass 01, 02... and that converts to ~12 first seconds of Unix timestamp. So 1970-01-01 00:00:03 is January.
Change your code to use mktime
$dataValue = date('n', mktime(0, 0, 0, $month, 1, date('Y')));
$startMonth = '01';
$endMonth = date('m');
foreach (range($startMonth, $endMonth) as $month) {
$time = mktime(0, 0, 0, $month, 1, date('Y'));
$date = date('n', $time);
$month = date('m', $time);
$monthName = date('F', $time);
echo "<td class='month' data-value='{$date}' data-id='{$incrementYear}'><a href='/Archive/view/{$incrementYear}/{$month}'>{$monthName}</a></td>";
}
Try this:
$startMonth = '01';
$endMonth = date('m');
foreach (range($startMonth, $endMonth) as $month) {
$dataValue = date('F', mktime(0, 0, 0, $month, 1, date('Y')));
$month = sprintf('%02d', $month);
echo '<td class="month" data-value="' . $dataValue . '" data-id="' . $month . '">' . $dataValue . '</td>';
}
Output:
JanuaryFebruaryMarchAprilMayJune
Change the $dataValue from
$dataValue = date('n', $month);
to
$dateObj = DateTime::createFromFormat('!m', $month);
echo $dateObj->format('F');
Hope this helps.
Try Below Code:
$start_date = date('Y-01-01');
$end_date = date('Y-m-01');
$loop_date = $start_date;
//loop through months
while(strtotime($loop_date)<=strtotime($end_date)){
echo date('F',strtotime($loop_date));
$loop_date = date('Y-m-d', strtotime("+1 months", strtotime($loop_date)));
}

Finding date range for week for particular month and year

Suppose I have a date available with me: 2016-07
I want to find date range of Week like this:
2016-07-03 to 2016-07-09
2016-07-10 to 2016-07-16
2016-07-17 to 2016-07-23
2016-07-24 to 2016-07-30
How can i achieve this?
I have tried using MySql but failed. Now I'm trying to do php.
This piece of code should do exactly what you want, if not please tell me or if you have questions
$date = "2016-07"; //Your date, can be any given date of this format
$monthAndYear = explode("-", $date);
$weeks = array();
$start = mktime(0, 0, 0, $monthAndYear[1], 1, $monthAndYear[0]);
$start -= 86400; //There are surely better ways
//find beginning if first week
do
{
$start += 86400;// Add one day
$tmp = date("N", $start);
}
while($tmp != 1);
//Get all weeks. If you want only those which are in the current month use this instead:
//while(date("n", ($start + 6 * 86400)) == $monthAndYear[1])
while(date("n", $start) == $monthAndYear[1])
{
$date = date("Y-m-d", $start);
$start += (6 * 86400);
$date .= " to ".date("Y-m-d", $start);
$weeks[] = $date;
$start += 86400;
}
echo "<pre>";
var_dump($weeks);
echo "</pre>";
The output is this:
array(4) {
[0]=>
string(24) "2016-07-04 to 2016-07-10"
[1]=>
string(24) "2016-07-11 to 2016-07-17"
[2]=>
string(24) "2016-07-18 to 2016-07-24"
[3]=>
string(24) "2016-07-25 to 2016-07-31"
}
With the second while option the result will be the same because the 31th is the end of the month and also the end of a week.
Please try the following code it produces the same output as yours:
function weeksRangesOfMonth($month, $year) {
$start_time = mktime(0, 0, 0, $month, 1, $year);
$start_time = mktime(0, 0, 0, $month, date('d', strtotime('First Monday', $start_time)), $year);
$end_time = mktime(0, 0, 0, $month, date('t', $start_time), $year);
$start = date("Y-m-d", $start_time);
$end = date("Y-m-d", $end_time);
for($date = $start; $date <= $end; $date = date('Y-m-d', strtotime($date. ' + 7 days'))) {
$time= strtotime($date);
$from = date("Y-m-d", strtotime('Last Sunday', $time));
$to = date("Y-m-d", strtotime('Next Saturday', $time));
echo "Start: ".$from.", End: ".$to;
echo "<br>";
}
}
weeksRangesOfMonth(7, 16);
Demo: http://codepad.org/mWSxphvA

Why does the following code return the second friday in November but first friday in December?

sorry if this is a duplicate. Why does the following code error so? It returns Dec 6th currently, the first Friday in December (asking on 8 Oct 2013)
$thisMonth = date('m');
$year = date("Y");
$thismonthName = date("M.", mktime(0, 0, 0, $thisMonth,0,$year));
if ($thisMonth < 12) {
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,1,$year));
} else {
$nextMonth = 1;
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,1,$nextYear));
}
$thisDate = date('M j', strtotime($nextmonthName . $year . "first friday"));
print ("second friday next month is " . $thisDate);
but modifying it to be only next month, like so,
$thisMonth = date('m');
$year = date("Y");
$thismonthName = date("M.", mktime(0, 0, 0, $thisMonth,0,$year));
if ($thisMonth < 12) {
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,0,$year));
} else {
$nextMonth = 1;
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,0,$nextYear));
}
$thisDate = date('M j', strtotime($nextmonthName . $year . "first friday"));
print ("second friday next month is " . $thisDate);
returns Nov 8th, the second Friday in November. Why is that?
You REALLY should investigate DateTime, DateInterval, DatePeriod classes. They make this sort of thing trivial.
$date = new DateTime();
$interval = DateInterval::createFromDateString('second friday of next month');
$date->add($interval);
echo 'Second Friday next month is ' . $date->format('Y-m-d');
Or to get 2nd Friday for next 3 months:
$date = new DateTime();
$recurrence_count = 3;
$interval = DateInterval::createFromDateString('second friday of next month');
$period = new DatePeriod($date, $interval, $recurrence_count);
foreach ($period as $dt) {
echo $dt->format('Y-m-d');
}
Your code is way too complicated.
$secondNextFriday = new DateTime('first friday of +2 months'); // First friday in december

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)

In PHP, is there an easy way to get the first and last date of a month?

I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?
$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
See date() in PHP documentation.
First day is always YYYY-MM-01, isn't it? Example: date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))
Last day is the previous day of the next month's first day:
$date = new DateTime("2008-09-01");
$date->modify("-1 day");
echo $date->format("Y-m-d");
The first day of the month is always 1.
So it will become
YYYY-MM-01
the last day can be calculated as:
<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>
OK, first is dead easy.
date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));
Last is a little trickier, but not much.
date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY));
If I remember my PHP date stuff correctly...
**edit - Gah! Beaten to it about a million times...
Edit by Pat:
Last day should have been
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
<?php
echo "Month Start - " . $monthStart = date("Y-m-1") . "<br/>";
$num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
echo "Monthe End - " . $monthEnd = date("Y-m-".$num);
?>
The easiest way to do this with PHP is
$dateBegin = strtotime("first day of last month");
$dateEnd = strtotime("last day of last month");
echo date("MYDATEFORMAT", $dateBegin);
echo "<br>";
echo date("MYDATEFORMAT", $dateEnd);
Or the last week
if (date('N', time()) == 7) {
$dateBegin = strtotime("-2 weeks Monday");
$dateEnd = strtotime("last Sunday");
} else {
$dateBegin = strtotime("Monday last week");
$dateEnd = strtotime("Sunday last week");
}
Or the last year
$dateBegin = strtotime("1/1 last year");
$dateEnd = strtotime("12/31 this year");
By the way #ZombieSheep solution
date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));
does not work it should be
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
Of course #Michał Słaby's accepted solution is the simplest.
Just to verify that I didn't miss any loose ends:
$startDay = 1;
if (date("m") == 1) {
$startMonth = 12;
$startYear = date("Y") - 1;
$endMonth = 12;
$endYear = date("Y") - 1;
}
else {
$startMonth = date("m") - 1;
$startYear = date("Y");
$endMonth = date("m") - 1;
$endYear = date("Y");
}
$endDay = date("d") - 1;
$startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));
$endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));
try this to get the number of days in the month:
$numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));
Example; I want to get first day and last day of current month.
$month = (int) date('F');
$year = (int) date('Y');
date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first
date('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last
When you run this for instance at date 2015-01-09, the first and last values will be sequentially;
2015-01-01
2015-01-31
Tested.
From here(get next month last day) that is marked as duplicated, so i can't add comment there, but people can got bad answers from there.
Correct one for last day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));
Correct one for first day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));
Code like this will be providing March from January, so that's not what could be expected.
echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));
proper way to build a relative date from now is:
//bad example - will be broken when generated at 30 of December (broken February)
echo date("Y-m-d", strtotime("now"))."\n";
echo date("Y-m-d", strtotime("now + 1 month"))."\n";
echo date("Y-m-d", strtotime("now + 2 month"))."\n";
echo date("Y-m-d", strtotime("now + 3 month"))."\n";
//good example, you can change first day to last day or any day
echo date("Y-m-d", strtotime("first day of this month"))."\n";
echo date("Y-m-d", strtotime("first day of next month"))."\n";
echo date("Y-m-d", strtotime("first day of +2 month"))."\n";
echo date("Y-m-d", strtotime("first day of +3 month"))."\n";
and the result will be:
2021-12-30
2022-01-30
2022-03-02
2022-03-30
2021-12-01
2022-01-01
2022-02-01
2022-03-01

Categories