Getting the next 10th of a month from now? - php

I am trying to find the next 10th of a month starting with today. So if today is the 27th of May, the next 10th is the 10th of June. If today is the 1st of August, the next 10th will be the 10th of August for example.
I know I can find the first day of the next month using
$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
Can I use that format for my case as well? If not, how could I achieve my goal?
Thanks a lot for helping! :)

strtotime is not able to do this in one call, but you could do something like:
<?php
$current_day = (int)date('j');
if ($current_day < 10) {
$firstDayNextMonth = date('Y-m-d', strtotime('+9 days', strtotime('first day of this month')));
} else {
$firstDayNextMonth = date('Y-m-d', strtotime('+9 days', strtotime('first day of next month')));
}
echo $firstDayNextMonth;
?>
Or simply just
$firstDayNextMonth = date('Y-m-d', strtotime('+9 days', strtotime('first day of ' . ((int)date('j') < 10 ? 'this' : 'next' ) . ' month')));

You can use the DateTime class:
$Date = new DateTime('first day of '.(date('j') < 10 ? 'this' : 'next').' month');
$Date->add(DateInterval::createFromDateString('9 days'));
var_dump($Date->format('Y-m-d'));
This will result in '2015-07-10' if it's '2015-06-10' today. Just use <= (or < 11) if it should return '2015-06-10' in that case.

Not sure if strtotime is able to do that.
A little trick can be:
$firstDayNextMonth = date('Y-m', strtotime('next month')) . '-10';

This might help a bit?
By using mktime you can simply define the day you want, even match more day sin a row more easely.
// set our day number
$daynum = 10;
$curDay = date('d');
// get current month
$curMonth = date('n');
// get current year
$curYear = date('Y');
$firstDayNextMonth = 'MissingNo';
if($curDay < $dayNum) {
$firstDayNextMonth = mktime(0, 0, 0, $curMonth, $daynum);
}
else {
// darnit, new year. but will we party?
if ($curMonth == 12) {
// use mktime to get a timestamp. We can become very precise with this...
$firstDayNextMonth = mktime(0, 0, 0, 0, $daynum, $curYear+1);
}
else {
$firstDayNextMonth = mktime(0, 0, 0, $curMonth+1, $daynum);
// let's test if we can have a little party or not.
}
}
echo date('D',$firstDayNextMonth) === date('D') ? 'matches! let\'s party!' : 'no match :( hide the beer';

$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
echo $firstDayNextMonth ."</br>";
$firstDayNextMonth = date('Y-m', strtotime('next month'));
echo $firstDayNextMonth."-10";
Is that what you want??

Very simple:
date('Y-m-d', strtotime('+9 days', strtotime('first day of this month', strtotime(sprintf('+%d days', (int) date('t') - 10)))));

Related

PHP: Week starts on Monday, but "monday this week" on a Sunday gets Monday next week

Here's a summary of the issue: On Sundays, strtotime('this week') returns the start of next week.
In PHP, the week seems to start on Monday. But, on any day except Sunday, this code
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
Outputs the date of this week's Monday, when it seems like it should be outputting last weeks Monday. It seems like, in this case, PHP is treating both Sunday and Monday as the the start of the week. It's now Monday, Dec 10, 2012, or 2012-12-10. date('Y-m-d', strtotime('sunday last week')) returns 2012-12-09 - yesterday.
Is this a bug, or am I missing something? It seems like a bug this obvious should be fairly well known, but I can't find anything about it. Is the only way to get the start of the week to use some special handling for Sundays?
$week_offset = (int) 'sunday' == date('l');
$week_start = strtotime("-$week_offset monday"); // 1 or 0 Mondays ago
As far as I can tell, this is a bug. I see no logical reason why strtotime('this week'); should return a future date. This is a pretty major bug. In my particular case, I had a leaderboard that showed the users with the most points since the beginning of the week. But on Sundays, it was empty because strtotime returned a timestamp for a future date. I was doubtful, because just I don't know how this could have gone unnoticed, but I couldn't find any other reports of this bug.
Thanks for all your time and help, folks.
This answer is late, but it's something that I've been struggling with. Every solution I've tried so far has malfunctioned for one reason or another. This is what I ended up with that worked for me. (though it may be look pretty, it at least works).
$thisMonday = strtotime('next Monday -1 week', strtotime('this sunday'));
Here is how you can get Monday of current week:
echo date("Y-m-d", strtotime(date('o-\\WW')));
It's not ideal but this is what I resorted to using:
if(date('N') == 7) {
$date = date('Y-m-d',strtotime('monday last week'));
} else {
$date = date('Y-m-d',strtotime('monday this week'));
}
I think the only problem with your coding is TimeZone.
Solution:
Set your own time Zone. Here is the example of my own time zone:
Example
date_default_timezone_set('Asia/Kolkata');
Set the above line before calling any time function.
Have a nice day.
I think instead of trying
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
you should try
echo date('Y-m-d', strtotime('monday last week'));
Try this code
// set current date
$date = date("m/d/Y");
$ts = strtotime($date); // also $ts = time();
// find the year and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
$i = 1; // 1 denotes the first day of week
$ts = strtotime($year.'W'.$week.$i);
echo $day = date("l", $ts); // generate the name of day
echo "<br>";
echo $day = date("Y-m-d", $ts); // generate the date
You will get the the date of current week, whether you are on monday you will get the date of that monday.
If you want the most recent monday:
function mostRecentMonday(){
if(date("w") == 1){
return strtotime("midnight today");
} else {
return strtotime("last monday");
}
}
Easy to modify to use DateTime, or, to even specify a different date to use as the base.
Based on Bryant answer :
$first_week_date = date('d F Y', strtotime('next Monday -1 week', strtotime('this sunday')));
$last_week_date = date('d F Y', strtotime('next Monday -1 week + 6 days', strtotime('this sunday')));
This is for thos looking for a friendly solution that works with any day.
function getWeekStart($week_start_day = "Monday") {
$week_days = array("Sunday"=>0,"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,);
if(!isset($week_days[$week_start_day])) {
return false;
} else {
$start_day = $week_days[$week_start_day];
$today = date("w");
$one_day = (60 * 60 * 24);
if($today < $start_day) {
$days_difference = 7 - ($start_day - $today);
} else {
$days_difference = ($today - $start_day);
}
$week_starts = strtotime(date("Y-m-d 00:00:00")) - ($one_day * $days_difference);
return $week_starts;
}
}
//Test: If today is Monday, it will return today's date
echo date("Y-m-d H:i:s", getWeekStart("Monday"));

how to get the first and last days of a given month

I wish to rewrite a mysql query which use month() and year() functions to display all the posts from a certain month which goes to my function as a 'Y-m-d' parameter format, but I don't know how can I get the last day of the given month date.
$query_date = '2010-02-04';
list($y, $m, $d) = explode('-', $query_date);
$first_day = $y . '-' . $m . '-01';
You might want to look at the strtotime and date functions.
<?php
$query_date = '2010-02-04';
// First day of the month.
echo date('Y-m-01', strtotime($query_date));
// Last day of the month.
echo date('Y-m-t', strtotime($query_date));
I know this question has a good answer with 't', but thought I would add another solution.
$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));
Try this , if you are using PHP 5.3+, in php
$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');
For finding next month last date, modify as follows,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
and so on..
cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.
// First date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
echo '<br />';
// Last date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, date('Y')));
$month = 10; // october
$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');
Basically:
$lastDate = date("Y-m-t", strtotime($query_d));
Date t parameter return days number in current month.
Print only current month week:
function my_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
$start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
if($currentWeek==1)
{$start_date = date('Y-m-01', strtotime($date));}
else if($currentWeek==5)
{$end_date = date('Y-m-t', strtotime($date));}
else
{}
return array($start_date, $end_date );
}
$date_range=list($start_date, $end_date) = my_week_range($new_fdate);
## Get Current Month's First Date And Last Date
echo "Today Date: ". $query_date = date('d-m-Y');
echo "<br> First day of the month: ". date('01-m-Y', strtotime($query_date));
echo "<br> Last day of the month: ". date('t-m-Y', strtotime($query_date));
In case of name of month this code will work
echo $first = date("Y-m-01", strtotime("January"));
echo $last = date("Y-m-t", strtotime("January"));

Calculating week of specified date

Does PHP calculate weeks as being Sunday - Saturday? For a given date I am trying to determine the beginning and ending date of it's week as well as the beginning date of the next/previous weeks. Everything works fine unless I pass in a Sunday and it thinks the date is in a previous week.
$start = $_GET['start'];
$year = date('Y', strtotime($start));
$week = date('W', strtotime($start));
$sunday = strtotime($year.'W'.$week.'0');
$next = strtotime('+7 Days', $sunday);
$prev = strtotime('-7 Days', $sunday);
echo '<p>week: ' . $week . '</p>';
echo '<p>sunday: ' . date('Y-m-d', $sunday) . '</p>';
echo '<p>next:' . date('Y-m-d', $next) . '</p>';
echo '<p>prev: ' . date('Y-m-d', $prev) . '</p>';
Outcome:
2011-01-09 (Sunday)
Week: 01
WRONG
2011-01-10 (Monday)
Week: 02
RIGHT
2011-01-15 (Saturday)
Week: 02
RIGHT
PHP doesn't think about weeks at all, if you're getting the wrong results, it's because your math is off. :)
$date = strtotime('2011-1-14');
$startingSunday = strtotime('-' . date('w', $date) . ' days', $date);
$previousSaturday = strtotime('-1 day', $startingSunday);
$nextWeekSunday = strtotime('+7 days', $startingSunday);
As Dr.Molle point out, the information about "W" is correct. Your problem is here:
$sunday = strtotime($year.'W'.$week.'0');
$sunday = strtotime($year.'W'.$week.'0');
$next = strtotime('+7 Days', $sunday);
$prev = strtotime('-7 Days', $sunday);
Then you called strtotime on a Timestamp object (sorry, I don't know the exact term).
The wrong type of parameter (timestamp and string are used not correctly) is the cause of the problem. Here's my piece of code to determine the week and the beginning day of the week:
<?php
$date = '2011/09/09';
while (date('w', strtotime($date)) != 1) {
$tmp = strtotime('-1 day', strtotime($date));
$date = date('Y-m-d', $tmp);
}
$week = date('W', strtotime($date));
echo '<p>week: ' . $week . '</p>';
?>
To fully understand, you should take a look on date & strtotime manual.
As defined in ISO_8601, what date('W') refers to, a week starts with monday.
But be careful and read about the ISO-week: http://en.wikipedia.org/wiki/ISO_week_date
Maybe the result is not always like expected.
example:
date('W',mktime(0, 0, 0, 1, 1, 2011))
It will return 52 instead of 01, because the first ISO-week of a year is the first week with at least 4 days in the given year.
As 2011-1-1 was a saturday, there are only 2 days, so 2011-1-1 is in ISO in the last week of 2010(52) and not in the first week of 2011.
The function date('W') uses the ISO-8601 definition, therefore Monday is the first day of the week.
In place of date('W') use strftime('%U').
Example:
$date = strtotime('2011-01-09');
echo strftime('%U',$date);
Outcome:
02
The code:
$date = strtotime('2012-05-06');
$sunday = date('Y-m-d', strtotime(strftime("%Y-W%U-0", $date)));
$sturday = date('Y-m-d', strtotime(strftime("%Y-W%U-6", $date)));
echo $sunday . "\n";
echo $saturday;
Outcome:
2012-05-06
2012-05-12

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

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