PHP date add 5 year to current date - php

I have this PHP code:
$end=date('Y-m-d');
I use it to get the current date, and I need the date 5 years in the future, something like:
$end=date('(Y + 5)-m-d');
How can I do this?

Try with:
$end = date('Y-m-d', strtotime('+5 years'));

Modifying dates based on this post
strtotime() is really powerful and allows you to modify/transform dates easily with it’s relative expressions too:
Procedural
$dateString = '2011-05-01 09:22:34';
$t = strtotime($dateString);
$t2 = strtotime('-3 days', $t);
echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
DateTime
$dateString = '2011-05-01 09:22:34';
$dt = new DateTime($dateString);
$dt->modify('-3 days');
echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
The stuff you can throw at strtotime() is quite surprising and very human readable. Have a look at this example looking for Tuesday next week.
Procedural
$t = strtotime("Tuesday next week");
echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
DateTime
$dt = new DateTime("Tuesday next week");
echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
Note that these examples above are being returned relative to the time now.
The full list of time formats that strtotime() and the DateTime constructor takes are listed on the PHP Supported Date and Time Formats page.
Another example, suitable for your case could be: based on this post
<?php
//How to get the day 3 days from now:
$today = date("j");
$thisMonth = date("n");
$thisYear = date("Y");
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear));
//1 week from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));
//4 months from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear));
//3 years, 2 months and 35 days from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
?>

Use this code to add years or months or days or hours or minutes or seconds to a given date
echo date("Y-m-d H:i:s", strtotime("+1 years", strtotime('2014-05-22 10:35:10'))); //2015-05-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 months", strtotime('2014-05-22 10:35:10')));//2014-06-22 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 days", strtotime('2014-05-22 10:35:10')));//2014-05-23 10:35:10
echo date("Y-m-d H:i:s", strtotime("+1 hours", strtotime('2014-05-22 10:35:10')));//2014-05-22 11:35:10
echo date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:36:10
echo date("Y-m-d H:i:s", strtotime("+1 seconds", strtotime('2014-05-22 10:35:10')));//2014-05-22 10:35:11
You can also subtract replacing + to -

$date = strtotime($row['timestamp']);
$newdate = date('d-m-Y',strtotime("+1 year",$date));

Its very very easy with Carbon.
$date = "2016-02-16"; // Or Your date
$newDate = Carbon::createFromFormat('Y-m-d', $date)->addYear(1);

Using Carbon:
$dt = Carbon::now();
echo $dt->addYears(5);

To add one year to todays date use the following:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

You may use DateInterval for this purpose;
$currentDate = new \DateTime(); //creates today timestamp
$currentDate->add(new \DateInterval('P5Y')); //this means 5 Years
and you can now format it;
$currentDate->format('Y-m-d');

Try below code, i hope it will be helpful for you
<?php
$current_date=strtotime(date('Y-m-d'));
echo $end = date('Y-m-d', strtotime('+5 years',$current_date));
?>

try this ,
$presentyear = '2013-08-16 12:00:00';
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )), date("d",strtotime($presentyear )), date("Y",strtotime($presentyear ))+5));
echo $nextyear;

try this:
$yearnow= date("Y");
$yearnext=$yearnow+1;
echo date("Y")."-".$yearnext;

Try this code and add next Days, Months and Years
// current month: Aug 2018
$n = 2;
for ($i = 0; $i <= $n; $i++){
$d = strtotime("$i days");
$x = strtotime("$i month");
$y = strtotime("$i year");
echo "Dates : ".$dates = date('d M Y', "+$d days");
echo "<br>";
echo "Months : ".$months = date('M Y', "+$x months");
echo '<br>';
echo "Years : ".$years = date('Y', "+$y years");
echo '<br>';
}

Related

add some days to current date in php

I have this code
<?php
$date =date(Y-m-d);
$day = 5;
$newdate= $date+$day
echo "today is:"$date;
echo "<br> and after 5 days is :"$newdate;
?>
I want the result is
today is :2016-11-2
and after 5 days is : 2016-11-7
Try this
$date = new DateTime(); // Creates new DatimeTime for today
$newdate = $date->modify( '+ 5 days' ); // Adds 5 days
echo $newdate->format( 'Y-m-d' ); // Echo and format the newdate to the wanted format
It should help you:
echo date('Y-m-d', strtotime($date. ' + 5 days'));
So it will be like follows:
<?php
$date = date('Y-m-d');
$newdate = date('Y-m-d', strtotime($date.' + 5 days'));
echo "today is: $date";
echo "<br> and after 5 days is: $newdate";
?>
You can use strtotime() function to add days to current date. Please see the below :
<?php
$date =date("Y-m-d");
$day = 5;
$newdate=date('Y-m-d', strtotime("+$day days"));
echo "today is:".$date;
echo "<br> and after 5 days is :".$newdate;
?>
it may help you
$date = "Mar 03, 2016";
$date = strtotime($date);
$date = strtotime("+7 day", $date);
echo date('M d, Y', $date);

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)

PHP: How to get Sunday and Saturday given a date input?

How can I get the Sunday and Saturday of the week given a specific date?
For example:
input: Monday, September 28, 2009
output should be:
Sunday, September 27, 2009 12:00 AM - Saturday, October 3, 2009 11:59 PM
I am thinking of using the date, strtotime, mktime and time php functions.
If you have a usable function then it is also fine with me.
Thanks in advance :)
Cheers,
Mark
You use strtotime() and date():
<?php
$s = 'Monday, September 28, 2009';
$time = strtotime($s);
$start = strtotime('last sunday, 12pm', $time);
$end = strtotime('next saturday, 11:59am', $time);
$format = 'l, F j, Y g:i A';
$start_day = date($format, $start);
$end_day = date($format, $end);
header('Content-Type: text/plain');
echo "Input: $s\nOutput: $start_day - $end_day";
?>
outputs:
Input: Monday, September 28, 2009
Output: Sunday, September 27, 2009 12:00 PM - Saturday, October 3, 2009 11:59 AM
<?php
date_default_timezone_set('Europe/London');
$datetime = new DateTime("2009-09-23 12:00:00");
// Saturday
$datetime->setISODate(2009, $datetime->format("W"), 6);
print "Saturday:" . $datetime->format(DATE_ATOM) . "\n";
// Sunday
$datetime->setISODate(2009, $datetime->format("W"), 0);
print "Sunday: " . $datetime->format(DATE_ATOM) . "\n";
?>
take a look at strtotime
i.e.
strtotime('next sunday', strtotime($your_date_string));
echo date("Y-m-d H:i:s", strtotime("last sunday", time()));
echo date("Y-m-d H:i:s", strtotime("next saturday", time()));
the issue with the 'correct' answer is, what if the supplied date is Sunday? Then it will give you the previous Sunday, instead of the current Sunday. Same issue with Saturday.
$s = 'Monday, September 28, 2009';
$time = strtotime($s);
if(date('D', $time) == "Sun"){
$start = strtotime(' 12pm', $time);
}
else {
$start = strtotime('last sunday, 12pm', $time);
}
if(date('D', $time) == "Sat"){
$start = strtotime(' 12pm', $time);
}
else {
$start = strtotime('next saturday, 12pm', $time);
}
$format = 'l, F j, Y g:i A';
$start_day = date($format, $start);
$end_day = date($format, $end);
header('Content-Type: text/plain');
echo "Input: $s\nOutput: $start_day - $end_day";
strtotime
$input = strtotime("Monday, September 28, 2009");
$nextSunday = strtotime("next Sunday",$input);
<?php
$date = strtotime('Monday, September 28, 2009 - 1 day');
$initialString = date('l, F d, Y g:i A', $date);
$end = date('l, F d, Y g:i A', strtotime( 'next saturday 11:59 pm', $date));
echo $initialString . ' - ' . $end;
output:
Sunday, September 27, 2009 12:00 AM - Saturday, October 03, 2009 11:59 PM
This is what your looking for. It is what I use.
$beginningOfWeek = date('Y-m-d H:i:s', strtotime('last Sunday'));
$endOfWeek = date('Y-m-d H:i:s', strtotime('+6 day', strtotime('last Sunday')) );
You may find my Date Time Helper much handy in this case , it can finish in 3 Lines
http://normandqq.github.io/Date-Time-Helper/
$date = '2013-08-11';
$monday = Model_DTHpr::getMondayByDate($date);
$sunday = Model_DTHpr::adjustDays("add",$monday,6);
Out Put:
2013-08-05 //Monday
2013-08-11 //Sunday
Get Sunday Php Code:
echo "Today Is : " . date("d-m-Y");
$dw = date( "w");
$dw = 7-$dw;
echo "\nNext Sunday Is" .date('d-m-Y', strtotime("+$dw days"));

Get first day of week in PHP?

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?
Here is what I am using...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.
Very simple to use strtotime function:
echo date("Y-m-d", strtotime('monday this week')), "\n";
echo date("Y-m-d", strtotime('sunday this week')), "\n";
It differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
Output for 4.3.5 - 5.2.17
2015-03-23
2015-03-22
Output for 4.3.0 - 4.3.4
2015-03-30
2015-03-29
Comparing at Edge-Cases
Relative descriptions like this week have their own context. The following shows the output for this week monday and sunday when it's a monday or a sunday:
$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
Againt it differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.5 - 5.0.5, 5.2.0 - 5.2.17
2015-03-16
2015-03-22
2015-03-23
2015-03-22
Output for 5.1.0 - 5.1.6
2015-03-23
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.0 - 4.3.4
2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());
Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.
Keep it simple :
<?php
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
?>
Source : PHP manual
NB: as some user commented the $dateTime value will be modified.
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday. From there you can simply calculate backwards to the day you want.
This question needs a good DateTime answer:-
function firstDayOfWeek($date)
{
$day = DateTime::createFromFormat('m-d-Y', $date);
$day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
return $day->format('m-d-Y');
}
var_dump(firstDayOfWeek('06-13-2013'));
Output:-
string '06-10-2013' (length=10)
This will deal with year boundaries and leap years.
EDIT: the below link is no longer running on the version of PHP stated. It is running on PHP 5.6 which improves the reliability of strtotime, but isn't perfect! The results in the table are live results from PHP 5.6.
For what it's worth, here is a breakdown of the wonky behavior of strtotime when determining a consistent frame of reference:
http://gamereplays.org/reference/strtotime.php
Basically only these strings will reliably give you the same date, no matter what day of the week you're currently on when you call them:
strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday");
Assuming Monday as the first day of the week, this works:
echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
The following code should work with any custom date, just uses the desired date format.
$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) );
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
I tested the code with PHP 5.2.17 Results:
Start: 30-07-2012
End: 05-08-2012
How about this?
$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
This is what I am using to get the first and last day of the week from any date.
In this case, monday is the first day of the week...
$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
Here I am considering Sunday as first & Saturday as last day of the week.
$m = strtotime('06-08-2012');
$today = date('l', $m);
$custom_date = strtotime( date('d-m-Y', $m) );
if ($today == 'Sunday') {
$week_start = date("d-m-Y", $m);
} else {
$week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));
}
if ($today == 'Saturday') {
$week_end = date("d-m-Y", $m);
} else {
$week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));
}
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
Output :
Start: 05-08-2012
End: 11-08-2012
How about this?
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
Try this:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
(from this forum thread)
This is the shortest and most readable solution I found:
<?php
$weekstart = strtotime('monday this week');
$weekstop = strtotime('sunday this week 23:59:59');
//echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
?>
strtotime is faster than new DateTime()->getTimestamp().
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));
You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.
$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):
<?php
function startOfWeek($aDate){
$d=strtotime($aDate);
return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
}
echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');
if($today_day != "Mon")
$start_of_week = date('Ymd', strtotime("last monday"));
if($today_day != "Sun")
$end_of_week = date('Ymd', strtotime("next sunday"));
If you want Monday as the start of your week, do this:
$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST). Let me show you how to do this.
This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):
class DateTimeUtilities {
public static function getPeriodFromMondayUntilFriday($offset = 'now') {
$now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
$today = $now->setTime(0, 0, 1);
$daysFromMonday = $today->format('N') - 1;
$monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
$saturday = $monday->add(new \DateInterval('P5D'));
return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
}
}
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
print $day->format('c');
print PHP_EOL;
}
This will return datetimes Monday-Friday for current week. To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday, thus:
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
print $day->format('c');
print PHP_EOL;
}
//prints
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00
Only interested in Monday, as the OP asked?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
You parse the date using strptime() and use date() on the result:
date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */
date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date
//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));
//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);
?>
(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)
I've come against this question a few times and always surprised the date functions don't make this easier or clearer. Here's my solution for PHP5 that uses the DateTime class:
/**
* #param DateTime $date A given date
* #param int $firstDay 0-6, Sun-Sat respectively
* #return DateTime
*/
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
$offset = 7 - $firstDay;
$ret = clone $date;
$ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
return $ret;
}
Necessary to clone to avoid altering the original date.
Another way to do it....
$year = '2014';
$month = '02';
$day = '26';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());
// 0=Sunday 6=Saturday
if($day!=0){
$newdate = $date->getTimestamp() - $day * 86400; //86400 seconds in a day
// Look for DST change
if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
if($old == 0){
$newdate -= 3600; //3600 seconds in an hour
} else {
$newdate += 3600;
}
}
$date->setTimestamp($newdate);
}
echo $date->format('D Y-m-d H:i:s');
The easiest way to get first day(Monday) of current week is:
strtotime("next Monday") - 604800;
where 604800 - is count of seconds in 1 week(60*60*24*7).
This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.
I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.
If the current day is a Sunday, then strtotime("monday this week") will return the day after.
To overcome this:
Caution: This is only valid for Australian/UK dates
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
Here's a one liner for the first day of last week, and the last day of last week as a DateTime object.
$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
->setTime(23, 59, 59);
Just to note that timestamp math can also be a solution. If you have in mind that 01.jan 1970 was a Thursday, then start of a week for any given date can be calculated with:
function weekStart($dts)
{ $res = $dts - ($dts+date('Z',$dts)+259200)%604800;
return $res + 3600*(date('I',$dts)-date('I',$res));
}
It is predictable for any timestamp and php version, using date-func ('Z', 'I') only for timezone and daylight-saving offsets. And it produces same results as:
strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');
and with (the best and the most elegant) mentioned:
strtotime('monday this week', $dts);

Getting last month's date in 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

Categories