Finding Last Day of Previous Month in PHP - php

I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.
<?php
$currentMonth = date('n');
$currentYear = date('Y');
if($currentMonth == 1) {
$lastMonth = 12;
$lastYear = $currentYear - 1;
}
else {
$lastMonth = $currentMonth -1;
$lastYear = $currentYear;
}
if($lastMonth < 10) {
$lastMonth = '0' . $lastMonth;
}
$lastDayOfMonth = date('t', $lastMonth);
$lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth;
$newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth));
?>
$lastDateOfPreviousMonth is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth is returning October 1, 2012. Where do I seem to be going wrong?
EDIT: If using date("t/m/Y", strtotime("last month")); or date('Y-m-d', strtotime('last day of previous month')); will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?

echo date('Y-m-d', strtotime('last day of previous month'));
//2012-09-30
or
$date = new DateTime();
$date->modify("last day of previous month");
echo $date->format("Y-m-d");
Later edit: php.net documentation - relative formats for strtotime(), DateTime and date_create()

There is a php function for this.
echo date("t/m/Y", strtotime("last month"));

First day of this month, minus 1 second.
echo date('Y-m-d',strtotime('-1 second',strtotime(date('m').'/01/'.date('Y'))));
Example here.

please try with below answer.
code:
echo date("t/m/Y", strtotime(date('Y-m')." -1 month"));
You will get last day of previous 12 months.
Example:
<?php
for ($i = 1; $i <= 12; $i++) {
$months[] = date("t/m/Y l", strtotime(date('Y-m')." -$i months"));
}
print_r($months);
?>
Output:
Array
(
[0] => 30/11/2018 Monday
[1] => 31/10/2018 Friday
[2] => 30/09/2018 Wednesday
[3] => 31/08/2018 Sunday
[4] => 31/07/2018 Thursday
[5] => 30/06/2018 Tuesday
[6] => 31/05/2018 Saturday
[7] => 30/04/2018 Thursday
[8] => 31/03/2018 Monday
[9] => 28/02/2018 Monday
[10] => 31/01/2018 Friday
[11] => 31/12/2017 Tuesday
)

You can use strtotime()'s zero handling functionality to achieve this also:
# Day Before
echo date('Y-m-d', strtotime('2016-03-00')); // 2016-02-29
# Year can be handled too
echo date('Y-m-d', strtotime('2016-01-00')); // 2015-12-31
# Month Before
echo date('Y-m-d', strtotime('2016-00-01')); // 2015-12-01
# Month AND Day
echo date('Y-m-d', strtotime('2016-00-00')); // 2015-11-30
Makes sense if you think of 00 as 'one less than the first (01)'.
So to achieve the objective of this question, 'last day of previous month' is a simple case of
date('your_format', strtotime('YYYY-ThisMonth-00'));
# So:
date('Y-m-d', strtotime('2016-11-00')); // 2016-10-31

Related

Date plus one month php [duplicate]

This question already has answers here:
PHP: Adding months to a date, while not exceeding the last day of the month
(7 answers)
Closed 6 years ago.
I have a small problem with dates in PHP.
When I made 31 + 1 month of January
with this code
$newDate = date('Y-m-d', strtotime('31-01-2016'.' + 1 month'));
echo $newDate;
it gives me 2 March but I need given me 29 February,
I need to add 1 month and is not 30days.
ditto for all dates:
for example
01 january + 1 month => 1 february
29 january + 1 month => 29 february
30 january + 1 month => 29 february
31 january + 1 month => 29 february
Thank for your help
I think you are looking for this type of dates.
<?php
$date = date('2016-01-31');
$currentMonth = date("m",strtotime($date));
$nextMonth = date("m",strtotime($date."+1 month"));
if($currentMonth==$nextMonth-1 && (date("j",strtotime($date)) != date("t",strtotime($date)))){
$nextDate = date('Y-m-d',strtotime($date." +1 month"));
}else{
$nextDate = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
}
echo "Next date would be : $nextDate";
?>
Check live demo : https://eval.in/610034
If date is 31-01-2016 then next date would be 29-02-2016
If date is 25-01-2016 then next date would be 25-02-2016
Simply try:
$date = new DateTime('2016-01-31');
$date->modify('last day of next month');
This of course only counts if you always go from the end of one moth to the end of the next one.
try this,
$date = "2016-01-29";
$date = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
echo $date;
https://3v4l.org/Y9PpV
How about something like this:
date_default_timezone_set('UTC');
$current_month = (int) date('m');
$year = date('y');
$newDate = date('Y-m-d', strtotime('31-1-2016'.' + 1 month'));
if($current_month == 12)
{
$new_month=0;
$year++;
}
$d = new DateTime( $year.'-'.($current_month+1).'-01' );
echo $d->format( 'Y-m-t' )."\n";
Change $current_month / $year based on your needs......

Finding the date for 29th last month, two months ago, etc

I'm looking to find the date of the 29th of this month, the 29th of next month, the 29th of last month and so on...
I know you can use this kind of code to find days of the week:
$friday_last = date("d/m/Y", strtotime("last Friday"));
$friday_due = date("d/m/Y", strtotime("this Friday"));
Is there a similar way to find a certain day (29th) of each month or would I have to use a different code?
You need to use DateTime() as it makes working with dates much easier. You'll notice I start by going to the first day of each month. That's so this doesn't break when you get to the 29th-30th of each month as weird date things start to happen.
echo (new DateTime())->modify('first day of this month')->format("29/m/Y");
echo (new DateTime())->modify('first day of previous month')->format("29/m/Y");
echo (new DateTime())->modify('first day of next month')->format("29/m/Y");
Demo
echo (new DateTime())->modify('first day of this month')->modify('-2 months')->format("29/m/Y");
Demo
Using date() with strtotime() will gives you 29th from each month within this year:
<?php
for ($i = 1; $i <= 12; $i++) {
$d = "2016-" . $i . "-29";
echo "29th of Month $i is: " . date("l", strtotime($d)) . '<br>';
}
?>
Output:
29th of Month 1 is: Friday
29th of Month 2 is: Monday
29th of Month 3 is: Tuesday
29th of Month 4 is: Friday
29th of Month 5 is: Sunday
29th of Month 6 is: Wednesday
29th of Month 7 is: Friday
29th of Month 8 is: Monday
29th of Month 9 is: Thursday
29th of Month 10 is: Saturday
29th of Month 11 is: Tuesday
29th of Month 12 is: Thursday
To create an array with current and next 11 months 29th day (for previous months replace +1 month with -1 month. In this example I use +1 to explain february issue, that is not present in past february):
$baseDate = date_create()->modify( 'first day of this month' );
$dates = array();
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
$dates[] = $newDate->modify( '+28 days' );
$baseDate->modify( '+1 month' );
}
The problem — as you can imagine — is with february:
foreach( $dates as $date )
{
echo $date->format( 'Y-m-d' ).PHP_EOL;
}
Will output:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-03-01 <-----
2017-03-29
2017-04-29
If you want a result like “29th month's day OR last month's day” modify above for loop in this way:
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
if( $newDate->modify( '+28 days' )->format( 'm' ) != $baseDate->format( 'm' ) )
{
$newDate->modify( 'last day of previous month' );
}
$dates[] = $newDate;
$baseDate->modify( '+1 month' );
}
Result:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-02-28 <-----
2017-03-29
2017-04-29
I'm not sure when this started, but now you can do so by using just date() and strtotime(), like this:
$d = date("Y-m-d 00:00:00", strtotime('first day of 2 months ago'));
$l = date("Y-m-d 00:00:00", strtotime('last day of 2 months ago'));
print_r($d);
print_r($l);
Assuming today (2023-02-01) The above will display:
2022-12-01 00:00:00
2022-12-31 00:00:00
Sample:
https://onlinephp.io/c/db73f

how do i get 5 dates of current week with php or jquery?

i have this and yesterday it worked fine, but not today.
$current_dayname = date("l");
$datemon = date("m-d-Y",strtotime('monday this week'));
$datetue = date("m-d-Y",strtotime("tuesday this week"));
$datewed = date("m-d-Y",strtotime("wednesday this week"));
$datethu = date("m-d-Y",strtotime("thursday this week"));
$datefri = date("m-d-Y",strtotime("friday this week"));
yesterday, $datemon through $datefri would get the values of 1-20-2014 through 1-24-2014, but today only tuesday through friday is working and monday is getting the date for next monday, not yesterday.
how can i get the dates of the 5 weekdays of the current week? so if it's wednesday for example, the 5 variables should be 2 for 2 days past, 1 for current day, and 2 for future days. know what i mean?
i'm going to guess that someone will ask if week starts with monday or sunday. doesn't really matter as long as script works, but the week starting on a monday is preferable.
An easier way to get those dates might be something like this:
$today = time();
$wday = date('w', $today);
$datemon = date('m-d-Y', $today - ($wday - 1)*86400);
$datetue = date('m-d-Y', $today - ($wday - 2)*86400);
$datewed = date('m-d-Y', $today - ($wday - 3)*86400);
$datethu = date('m-d-Y', $today - ($wday - 4)*86400);
$datefri = date('m-d-Y', $today - ($wday - 5)*86400);
I would also recommend using an array instead of 5 different variables, but that's a separate concern.
Simple DateTime::setISODate() example:
$dt = new DateTime();
$dates = [];
for ($d = 1; $d <= 5; $d++) {
$dt->setISODate($dt->format('o'), $dt->format('W'), $d);
$dates[$dt->format('D')] = $dt->format('m-d-Y');
}
print_r($dates);
will output:
Array
(
[Mon] => 01-20-2014
[Tue] => 01-21-2014
[Wed] => 01-22-2014
[Thu] => 01-23-2014
[Fri] => 01-24-2014
)
demo

php - find date for same day of week for last year

So, in PHP i'm trying to return a date value for last year based on the same day of week.
EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.
I was just doing it simply by -364 but then that was failing on leap years. I came across another function :
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
however, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.
I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.
Any suggestions?
Thanks!
How about this, using PHP's DateTime functionality:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
$newDate = '2011-12-19';
date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);
$dateFormat = 'Y-m-d l w W';
echo "This date: ", date($dateFormat, $newDate), "\n";
echo "Old date : ", date($dateFormat, $oldDate);
That gives:
This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
Use strtotime() to get a date, for the same week last year.
Use the format {$year}-W{$week}-{$weekday}, like this:
echo date("Y-m-d", strtotime("2010-W12-1"));
And you can do that for as long back you wan't:
<?php
for($i = 2011; $i > 2000; $i--)
echo date("Y-m-d", strtotime($i."-W12-1"));
?>
Make it easier :)
echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));
Edit: I forgot to write output: :)
2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
<?php
$date = "2020-01-11";
$newdate = date("Y-m-d",strtotime ( '-1 year' , strtotime ( $date ) )) ;
echo $newdate;
?>
ref https://www.nicesnippets.com/blog/how-to-get-previous-year-from-date-in-php

Finding date range for current week, month and year

Suppose I have a date available with me:
2011-04-05 (i.e., 5th April, 2011)
I want to find date range for Current Week, Month and Year
Current Week: 3rd April to 9th April
Current Month: 1st April to 30 April
Current Year: 1st Jan to 31 Dec
I do understand that current year would be always 1st Jan to 31Dec, but what about current month and week, How can I find it?
Edit:
How can I find date, which is 10 days earlier or later from a given date.
Example:
Suppose today's date is 6th April, 2011
10 day's earlier: 28 March, 2011
10 day's later: 15 April, 2011
Any thoughts on this, guys?
function rangeMonth ($datestr) {
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"start" => date ('Y-m-d', strtotime ('first day of this month', $dt)),
"end" => date ('Y-m-d', strtotime ('last day of this month', $dt))
);
}
function rangeWeek ($datestr) {
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"start" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
"end" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
);
}
print_r (rangeMonth('2011-4-5')); // format: YYYY-M-D
print_r (rangeWeek('2011-4-5'));
output for rangeMonth()
Array
(
[start] => 2011-04-01
[end] => 2011-04-30
)
output for rangeWeek()
Array
(
[start] => 2011-04-04
[end] => 2011-04-08
)
Notice: functions like getdate(), date(), etc. throw Warning if default time zone is not set in php.ini.
you can use strtotime
example :
date('d.m.Y',strtotime('last day of this month'))
date('d.m.Y',strtotime('last monday')) // for first day of this week
This solution is simple, and it takes in consideration when the current day is Monday or Sunday.
NOTE: Using strtotime('last monday') may work if the day is other than Monday, otherwise it will return the previous Monday. Because of that we should use strtotime('last monday', strtotime('tomorrow')) and it will work for any day of the current week =)
Solution:
$monday = strtotime('last monday', strtotime('tomorrow'));
$sunday = strtotime('+6 days', $monday);
echo "<P>". date('d-M-Y', $monday) . " to " . date('d-M-Y', $sunday) . "</P>";
The following code will give you the start and last date of a week:
$today = getdate();
print_r($today);
echo "<br/>";
$weekStartDate = $today['mday'] - $today['wday'];
$weekEndDate = $today['mday'] - $today['wday']+6;
echo "<br/>";
echo "<br/>";
echo "week start date:".$weekStartDate;
echo "<br/>";
echo "week end date:".$weekEndDate;
Hope it helps...
Check out the getdate function, there are a few examples of how to use it on the manual page I linked. I think it will return everything you're looking for,
Working example it properly handles the Monday issue
<?php
$monday = strtotime("last monday");
$monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
$this_week_sd = date("Y-m-d",$monday);
$this_week_ed = date("Y-m-d",$sunday);
echo "Current week range from $this_week_sd to $this_week_ed ";
?>
Today is Tuesday, August 27th 2019
This week is from Monday, August 26th 2019 to Sunday, September 1st 2019
php > $date = new DateTime('Sunday');
php > echo $date->format('Y-m-d H:i:s');
2019-09-01 00:00:00
php > $date = new DateTime('Tuesday');
php > echo $date->format('Y-m-d H:i:s');
2019-08-27 00:00:00
php > $date = new DateTime('Monday');
php > echo $date->format('Y-m-d H:i:s');
2019-09-02 00:00:00
php > $date = new DateTime('Monday this week');
php > echo $date->format('Y-m-d H:i:s');
2019-08-26 00:00:00

Categories