Getting last month's date in php - php

I want to get last month's date. I wrote this out:
$prevmonth = date('M Y');
Which gives me the current month/year. I can't tell if I should use strtotime, mktime. Something to the timestamp? Do I need to add something afterwards to reset so that the date isn't set to last month throughout everything for all timestamps on my site? I'm trying to RTM but it's hard for me to figure this out.

It's simple to get last month date
echo date("Y-n-j", strtotime("first day of previous month"));
echo date("Y-n-j", strtotime("last day of previous month"));
at November 3 returns
2014-10-1
2014-10-31

echo strtotime("-1 month");
That will output the timestamp for last month exactly. You don't need to reset anything afterwards. If you want it in an English format after that, you can use date() to format the timestamp, ie:
echo date("Y-m-d H:i:s",strtotime("-1 month"));

$prevmonth = date('M Y', strtotime("last month"));

Incorrect answers are:
$lastMonth = date('M Y', strtotime("-1 month"));
$lastDate = date('Y-m', strtotime('last month'));
The reason is if current month is 30+ days but previous month is 29 and less $lastMonth will be the same as current month.
e.g.
If $currentMonth = '30/03/2016';
echo $lastMonth = date('m-Y', strtotime("-1 month")); => 03-2016
echo $lastDate = date('Y-m', strtotime('last month')); => 2016-03
The correct answer will be:
echo date("m-Y", strtotime("first day of previous month")); => 02-2016
echo sprintf("%02d",date("m")-1) . date("-Y"); => 02-2016
echo date("m-Y",mktime(0,0,0,date("m")-1,1,date("Y"))); => 02-2016

echo date('Y',strtotime("-1 year")); //last year<br>
echo date('d',strtotime("-1 day")); //last day<br>
echo date('m',strtotime("-1 month")); //last month<br>

Found this one wrong when the previous months is shorter than current.
echo date("Y-m-d H:i:s",strtotime("-1 month"));
Try on March the 30th and you will get 2012-03-01 instead of 2012-02...
Working out on better solution...

if you want to get just previous month, then you can use as like following
$prevmonth = date('M Y', strtotime('-1 months'));
if you want to get same days of previous month, Then you can use as like following ..
$prevmonth = date('M Y d', strtotime('-1 months'));
if you want to get last date of previous month , Then you can use as like following ...
$prevmonth = date('M Y t', strtotime('-1 months'));
if you want to get first date of previous month , Then you can use as like following ...
$prevmonth = date('M Y 1', strtotime('-1 months'));

public function getLastMonth() {
$now = new DateTime();
$lastMonth = $now->sub(new DateInterval('P1M'));
return $lastMonth->format('Ym');
}

Use this short code to get previous month for any given date:
$tgl = '25 january 2012';
$prevmonth = date("M Y",mktime(0,0,0,date("m", strtotime($tgl))-1,1,date("Y", strtotime($tgl))));
echo $prevmonth;
The result is December 2011.
Works on a month with shorter day with previous month.

$lastMonth = date('M Y', strtotime("-1 month"));
var_dump($lastMonth);
$lastMonth = date('M Y', mktime(0, 0, 0, date('m') - 1, 1, date('Y')));
var_dump($lastMonth);

Simply get last month.
Example:
Today is: 2020-09-02
Code:
echo date('Y-m-d', strtotime(date('Y-m-d')." -1 month"));
Result:
2020-08-02

You can use strtotime, which is great in this kind of situations :
$timestamp = strtotime('-1 month');
var_dump(date('Y-m', $timestamp));
Will get you :
string '2009-11' (length=7)

$time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
$lastMonth = date("d-m-Y", $time);
OR
$lastMonth = date("m-Y", mktime() - 31*3600*24);
works on 30.03.2012

Oh I figured this out, please ignore unless you have the same problem i did in which case:
$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));

This question is quite old but here goes anyway. If you're trying to get just the previous month and the day does not matter you can use this:
$date = '2014-01-03';
$dateTime = new DateTime($date);
$lastMonth = $dateTime->modify('-' . $dateTime->format('d') . ' days')->format('F Y');
echo $lastMonth; // 'December 2013'

The best solution I have found is this:
function subtracMonth($currentMonth, $monthsToSubtract){
$finalMonth = $currentMonth;
for($i=0;$i<$monthsToSubtract;$i++) {
$finalMonth--;
if ($finalMonth=='0'){
$finalMonth = '12';
}
}
return $finalMonth;
}
So if we are in 3(March) and we want to subtract 5 months that would be
subtractMonth(3,5);
which would give 10(October). If the year is also desired, one could do this:
function subtracMonth($currentMonth, $monthsToSubtract){
$finalMonth = $currentMonth;
$totalYearsToSubtract = 0;
for($i=0;$i<$monthsToSubtract;$i++) {
$finalMonth--;
if ($finalMonth=='0'){
$finalMonth = '12';
$totalYearsToSubtract++;
}
}
//Get $currentYear
//Calculate $finalYear = $currentYear - $totalYearsToSubtract
//Put resulting $finalMonth and $finalYear into an object as attributes
//Return the object
}

It works for me:
Today is: 31/03/2012
echo date("Y-m-d", strtotime(date('m', mktime() - 31*3600*24).'/01/'.date('Y').' 00:00:00')); // 2012-02-01
echo date("Y-m-d", mktime() - 31*3600*24); // 2012-02-29

If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months')); what? first date will always be 1 :D

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;
}

Display next first Sunday without specifying month in PHP [duplicate]

I can get the Monday of this week with:
$monday = date_create()->modify('this Monday');
I would like to get with the same ease the 1st of this month. How can I achieve that?
Here is what I use.
First day of the month:
date('Y-m-01');
Last day of the month:
date('Y-m-t');
Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:
<?php
// First day of this month
$d = new DateTime('first day of this month');
echo $d->format('jS, F Y');
// First day of a specific month
$d = new DateTime('2010-01-19');
$d->modify('first day of this month');
echo $d->format('jS, F Y');
// alternatively...
echo date_create('2010-01-19')
->modify('first day of this month')
->format('jS, F Y');
In PHP 5.4+ you can do this:
<?php
// First day of this month
echo (new DateTime('first day of this month'))->format('jS, F Y');
echo (new DateTime('2010-01-19'))
->modify('first day of this month')
->format('jS, F Y');
If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date():
<?php
echo date('Y-m-01'); // first day of this month
echo "$year-$month-01"; // first day of a month chosen by you
This is everything you need:
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());
$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());
$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());
echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';
echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';
echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
Currently I'm using this solution:
$firstDay = new \DateTime('first day of this month');
$lastDay = new \DateTime('last day of this month');
The only issue I came upon is that strange time is being set. I needed correct range for our search interface and I ended up with this:
$firstDay = new \DateTime('first day of this month 00:00:00');
$lastDay = new \DateTime('first day of next month 00:00:00');
I use a crazy way to do this is using this command
$firstDay=date('Y-m-d',strtotime("first day of this month"));
$lastDay=date('Y-m-d',strtotime("last day of this month"));
Thats all
In php 5.2 you can use:
<? $d = date_create();
print date_create($d->format('Y-m-1'))->format('Y-m-d') ?>
Ugly, (and doesn't use your method call above) but works:
echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));
You can do it like this:
$firstday = date_create()->modify('first day January 2010');
using date method, we should be able to get the result.
ie; date('N/D/l', mktime(0, 0, 0, month, day, year));
For Example
echo date('N', mktime(0, 0, 0, 7, 1, 2017)); // will return 6
echo date('D', mktime(0, 0, 0, 7, 1, 2017)); // will return Sat
echo date('l', mktime(0, 0, 0, 7, 1, 2017)); // will return Saturday
I use this with a daily cron job to check if I should send an email on the first day of any given month to my affiliates. It's a few more lines than the other answers but solid as a rock.
//is this the first day of the month?
$date = date('Y-m-d');
$pieces = explode("-", $date);
$day = $pieces[2];
//if it's not the first day then stop
if($day != "01") {
echo "error - it's not the first of the month today";
exit;
}
Timestamp for start of this month and very last second of current month.
You can add 00:00:00 or just reference "today"
Alternative:
$startOfThisMonth = strtotime("first day of this month",strtotime("today"));
OR
$startOfThisMonth = strtotime("first day of this month 00:00:00");
$endOfThisMonth = strtotime("first day of next month",$startOfThisMonth)-1;
I am providing this answer as an alternative one liner if the DateTime object is not preferred
Basically, I get the current day number, reduce it by one then take that number of days from itself ("today" which automatically resets the clock to 00:00:00 too) and you get the start of the month.
$startOfMonth = strtotime("today - ".(date("j")-1)." days");
If you're using composer, you can install carbon:
composer require nesbot/carbon
This is then as simple as:
use Carbon/Carbon;
$startOfMonth = Carbon::now()->startOfMonth()->toDateTime();

How to get Dates of Previous or Next Months in PHP?

I know that date("Y"), date("m") and date("d") will return current Year (2013), Month (07) and Date (11) respectively.
I am working with date Format: "2013-07-11". I have current date like this. Now I want to get the value "2013-06-11" and "2013-08-11" somehow using PHP.
What might be the code to get this values (Last Month's Same Date, and Next Month's Same Date)?
I tried:
$LastMonth = date ("m") - 1;
$LastDate = date("Y") . "-0" . $LastMonth . "-" . date("d");
But this will return error when it is October. In October it will show "2013-010-11".
What can be a better solution? Can anyone help me?
Use it with PHP's strtotime():
echo date('Y-m-d', strtotime('+1 month')); //outputs 2013-08-11
echo date('Y-m-d', strtotime('-1 month')); //outputs 2013-06-11
$date = new DateTime( "2013-07-11");
$date->modify("+1 month");
echo $date->format(‘l, F jS, Y’);
Try this
$lst_month=mktime(0,0,0,date('m')-1,date('d'),date('Y'));
echo "M<br>". date("Y-m-d",$lst_month);
$next_month=mktime(0,0,0,date('m')+1,date('d'),date('Y'));
echo "M<br>". date("Y-m-d",$next_month);
$nextmonth=date("dmy",strtotime("+1 month"));
$lastmonth=date("dmy",strtotime("-1 month"));

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

The first day of the current month in php using date_modify as DateTime object

I can get the Monday of this week with:
$monday = date_create()->modify('this Monday');
I would like to get with the same ease the 1st of this month. How can I achieve that?
Here is what I use.
First day of the month:
date('Y-m-01');
Last day of the month:
date('Y-m-t');
Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:
<?php
// First day of this month
$d = new DateTime('first day of this month');
echo $d->format('jS, F Y');
// First day of a specific month
$d = new DateTime('2010-01-19');
$d->modify('first day of this month');
echo $d->format('jS, F Y');
// alternatively...
echo date_create('2010-01-19')
->modify('first day of this month')
->format('jS, F Y');
In PHP 5.4+ you can do this:
<?php
// First day of this month
echo (new DateTime('first day of this month'))->format('jS, F Y');
echo (new DateTime('2010-01-19'))
->modify('first day of this month')
->format('jS, F Y');
If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date():
<?php
echo date('Y-m-01'); // first day of this month
echo "$year-$month-01"; // first day of a month chosen by you
This is everything you need:
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());
$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());
$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());
echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';
echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';
echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
Currently I'm using this solution:
$firstDay = new \DateTime('first day of this month');
$lastDay = new \DateTime('last day of this month');
The only issue I came upon is that strange time is being set. I needed correct range for our search interface and I ended up with this:
$firstDay = new \DateTime('first day of this month 00:00:00');
$lastDay = new \DateTime('first day of next month 00:00:00');
I use a crazy way to do this is using this command
$firstDay=date('Y-m-d',strtotime("first day of this month"));
$lastDay=date('Y-m-d',strtotime("last day of this month"));
Thats all
In php 5.2 you can use:
<? $d = date_create();
print date_create($d->format('Y-m-1'))->format('Y-m-d') ?>
Ugly, (and doesn't use your method call above) but works:
echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));
You can do it like this:
$firstday = date_create()->modify('first day January 2010');
using date method, we should be able to get the result.
ie; date('N/D/l', mktime(0, 0, 0, month, day, year));
For Example
echo date('N', mktime(0, 0, 0, 7, 1, 2017)); // will return 6
echo date('D', mktime(0, 0, 0, 7, 1, 2017)); // will return Sat
echo date('l', mktime(0, 0, 0, 7, 1, 2017)); // will return Saturday
I use this with a daily cron job to check if I should send an email on the first day of any given month to my affiliates. It's a few more lines than the other answers but solid as a rock.
//is this the first day of the month?
$date = date('Y-m-d');
$pieces = explode("-", $date);
$day = $pieces[2];
//if it's not the first day then stop
if($day != "01") {
echo "error - it's not the first of the month today";
exit;
}
Timestamp for start of this month and very last second of current month.
You can add 00:00:00 or just reference "today"
Alternative:
$startOfThisMonth = strtotime("first day of this month",strtotime("today"));
OR
$startOfThisMonth = strtotime("first day of this month 00:00:00");
$endOfThisMonth = strtotime("first day of next month",$startOfThisMonth)-1;
I am providing this answer as an alternative one liner if the DateTime object is not preferred
Basically, I get the current day number, reduce it by one then take that number of days from itself ("today" which automatically resets the clock to 00:00:00 too) and you get the start of the month.
$startOfMonth = strtotime("today - ".(date("j")-1)." days");
If you're using composer, you can install carbon:
composer require nesbot/carbon
This is then as simple as:
use Carbon/Carbon;
$startOfMonth = Carbon::now()->startOfMonth()->toDateTime();

Categories