Find the date for next 15th using php - php

I am trying to find the date when it's next 15th.
I came across this Get the date of the next occurrence of the 18th but this shows the today date if its' 18th..I want to see August 18th 20111.
Is there any way to get the next 15th?
regards

// dynamic typing FTW
$next15th = mktime(0, 0, 0, date('n') + (date('j') >= 15), 15);
echo date('Y-m-d', $next15th);

Looking at the link you provided above, I would assume you change the following:
$nextDay = 18;
I'd change that to:
$nextDay = 15;

if(date('d') >= 15)
$date = date('Y-m', strtotime('+1 month')).-'.$nextDay
else
$date = date('Y-m').'-'.$nextDay;

Related

How to set the "first day of the week" to Thursday in PHP

I want to set the first day of the week to Thursday (not Sunday or Monday), because it's the company's cut-off date.
I already have a code to determine the current week number of a date but it starts in Sunday or Monday.
How to modify these to my preference?
function findweek($date) {
$monthstart=date("N",strtotime(date("n/l/Y",strtotime($date))));
$newdate=(date("j",strtotime($date))+$monthstart)/7;
$ddate=floor($newdate);
if($ddate != $date) {
$ddate++;
}
return $ddate;
}
http://php.net/manual/en/datetime.formats.relative.php says that as of PHP version 5.6.23, 7.0.8 "Weeks always start on monday. Formerly, sunday would also be considered to start a week." That said, is your problem that the number of weeks returned might be incorrect depending on whether today falls on or before Thursday of the current week? Maybe try something like this:
$date = new DateTime();
$week = intval($date->format('W'));
$day = intval($date->format('N'));
echo $day < 4 ? $week-1 : $week;
If subtracting 1 isn't the answer you could play around with addition/subtraction, comparing the result with the actual answer you know to be true until you get the right formula. Hope this helps!
This should work.
function findweek($date, $type = "l") {
$time = strtotime($date);
return date($type, mktime(0, 0, 0, date("m", $time) , date("d", $time)-date("d", $time)+1, date("Y", $time)));
}
echo findweek('2015-09-16');

How do I get last year's start and end date?

How can I get last year's start and end date using PHP code? Is it possible?
The first day is always January 1, the last day is always December 31. You're really only changing the year attached to it. Depending on how you want the date formatted, you have a couple possibilities...
If you just want to display the physical date:
$year = date('Y') - 1; // Get current year and subtract 1
$start = "January 1st, {$year}";
$end = "December 31st, {$year}";
If you need the timestamp for both those dates:
$year = date('Y') - 1; // Get current year and subtract 1
$start = mktime(0, 0, 0, 1, 1, $year);
$end = mktime(0, 0, 0, 12, 31, $year);
Very simple stuff. You can manually specify which year if you wanted too. The premise is the same.
You can do it by using the below. Hope it helps someone.
//to get start date of previous year
echo date("d-m-y",strtotime("last year January 1st"));
//to get end date of previous year
echo date("d-m-y",strtotime("last year December 31st"));
start date of the year :
mktime(0,0,0,1,1,$year);
end date of the year :
mktime(0,0,0,1,0,$year+1);
Check this Stuff
$currentY = date('Y');
$lastyearS = mktime(0, 0, 0, 1, 1, $currentY-1 )."<br/>";
$lastyearE = mktime(0, 0, 0, 12, 31, $currentY-1 )."<br/>";
echo date('Y-m-d',$lastyearS)."<br/>";echo date('Y-m-d',$lastyearE);
Suppose if your current month is February or the month which has 30 days
echo date('Y-12-t', strtotime(date('Y-m-d'))); // if current month is february (2015-02-01) than it gives 2015-02-28
will give you inaccurate results
Solution:
So to get accurate result for the end date of an year, try the code below
$start_date = date("Y-01-01", strtotime("-1 year"));// get start date from here
$end_date = date("Y-12-t", strtotime($start_date));
(OR)
$last_year_last_month_date = date("Y-12-01", strtotime("-1 year"));
$end_date = date("Y-12-t", strtotime($last_year_last_month_date));

Trying to get the number of the month before of the current month

I'm trying to get the number of month before of the current month (now is 04 (april), so I'm trying to get 03). I'm trying this:
date('m')-1;
but I get 3. But what I want is to get 03.
The correct way to do this really is:
date('m', strtotime('-1 month'));
As you will see strange things happen in January with other answers.
The currently accepted response will result in an incorrect answer whenever the day of the month (for the current day) is a larger number than the last day of the month for the previous month.
e.g. The result of executing date('m', strtotime('-1 month')); on March 29th (in a non-leap-year) will be 03, because 29 is larger than any day of the month for February, and thus strtotime('-1 month') will actually return March 1st.
Instead, use the following:
date('n') - 1;
You may be surprised, but date() function manual page has an exact example of what you need:
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
The result of your calculation is a number. If you want to format it like a string, you can use:
$result = date('m')-1;
$string_result = sprintf("%02s", $result);
Edit: Note that this is only a partial solution to format a number like a string.
intval(date('m'))
for the current month
(intval(date('m'))-1)%12
for the previous month, also for december/january
date('m', strtotime('last month'));
This will work regardless of whether or not you're in January
This works too.
printf("%02s", (date('m') - 1));
This should do it for you...
str_pad(date('m')-1, 2, '0', STR_PAD_LEFT);

How to find first day of the next month and remaining days till this date with PHP

How can I find first day of the next month and the remaining days till this day from the present day?
Thank you
Create a timestamp for 00:00 on the first day of next month:
$firstDayNextMonth = strtotime('first day of next month');
The number of days til that date is the number of seconds between now and then divided by (24 * 60 * 60).
$daysTilNextMonth = ($firstDayNextMonth - time()) / (24 * 3600);
$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
For getting first day after two months from current
$firstDayAfterTwoMonths = date('Y-m-d', strtotime('first day of +2 month'));
You can use DateTime object like this to find out the first day of next month like this:
$date = new DateTime('first day of next month');
You can do this to know how many days left from now to the first day of next month:
$date = new DateTime('now');
$nowTimestamp = $date->getTimestamp();
$date->modify('first day of next month');
$firstDayOfNextMonthTimestamp = $date->getTimestamp();
echo ($firstDayOfNextMonthTimestamp - $nowTimestamp) / 86400;
The easiest and quickest way is to use strtotime() which recognizes 'first day next month';
$firstDayNextMonth = date('Y-m-d', strtotime('first day next month'));
Since I googled this and came to this answer, I figured I'd include a more modern answer that works for PHP 5.3.0+.
//Your starting date as DateTime
$currentDate = new DateTime(date('Y-m-d'));
//Add 1 month
$currentDate->add(new DateInterval('P1M'));
//Get the first day of the next month as string
$firstDayOfNextMonth = $currentDate->format('Y-m-1');
You can get the first of the next month with this:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
With this example, $thefirst will be the UNIX timestamp for the first of the next month. Use date to format it to your liking.
This will give you the remaining days in the month:
$now = getdate();
$months = array(
31,
28 + ($now['year'] % 4 == 0 ? 1 : 0), // Support for leap years!
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
);
$days = $months[$now['mon'] - 1];
$daysleft = $days - $now['mday'];
The number of days left will be stored in $daysleft.
Hope this helps!
$firstDayNextMonth = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
As another poster has mentioned the DateInterval object does not give accurate results for the next month when you use dates such as 1/31/2016 or 8/31/2016 as it skips the next month. My solution was to still use the DateInterval object but reformat your current date to be the first day of the current month prior to utilizing the DateInterval.
$currentDate = '8/31/2016';
$date = new DateTime(date("n", strtotime($currentDate))."/1/".date("Y", strtotime($currentDate)));
//add 1 month
$date->add(new DateInterval('P1M'));
$currentDate=$date->format('m/1/Y');
echo($currentDate);
easiest way to get the last day of the month
date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));
I took mattbasta's approach because it's able to get the 'first day of next month' with a given date, but there is a tiny problem in calculating the $nextmonth. The fix is as below:
$now = getdate();
$nextmonth = ($now['mon'] + 1) % 13 + 1;
$year = $now['year'];
if($nextmonth == 1)
$year++;
else
$nextmonth--;
$thefirst = gmmktime(0, 0, 0, $nextmonth, $year);
I initially thought about using a DateInterval object (as discussed above in another answer) but it is not reliable. For example, if the current DateTime is 31 January and then we add on a month (to get the next month) then it will skip February completely!
Here is my solution:
function start_of_next_month(DateTime $datetime)
{
$year = (int) $datetime->format('Y');
$month = (int) $datetime->format('n');
$month += 1;
if ($month === 13)
{
$month = 1;
$year += 1;
}
return new DateTime($year . '-' . $month . '-01');
}
Even easier way to get first and last day of next month
$first = strttotime("first day of next month");
$last = strttotime("last day of next month");
You could do something like this. To have this functionality, you need to make use of a php library available in https://packagist.org/packages/ishworkh/navigable-date.
With that is really easy to do what you're asking for here.
For e.g:
$format = 'Y-m-d H:i:s';
$Date = \NavigableDate\NavigableDateFacade::create('2017-02-24');
var_dump($Date->format($format));
$resetTime = true;
$resetDays = true;
$NextMonth = $Date->nextMonth($resetTime, $resetDays);
var_dump($NextMonth->format($format));
$DayUntilFirstOfNextMonth = $NextMonth->getDifference($Date);
var_dump('Days left:' . $DayUntilFirstOfNextMonth->format('%d'));
gives you ouput:
string(19) "2017-02-24 00:00:00"
string(19) "2017-03-01 00:00:00"
string(11) "Days left:5"
Note: Additionally this library let you navigate through dates by day(s), week(s), year(s) forward or backward. For more information look into its README.
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
To get the first day of next month a clean solution:
<?php
$date = new DateTimeInmutable('now');
$date->modify('first day of next month');//here the magic occurs
echo $date->format('Y-m-d') . '\n';
Since you just want to calculate it I suggest using DateTimeInmutable class.
using the class DateTime and $date->modify('first day of next month'); will modify your original date value.
$month = date('m')+1;
if ($month<10) {
$month = '0'.$month;
}
echo date('Y-').$month.'-01';
Simplest way to achieve this. You can echo or store into variable.
I came up with this for my needs:
if(date('m') == 12) { $next_month = 1; } else { $next_month = date('m')+1; }
if($next_month == 1) { $year_start = date('Y')+1; } else { $year_start = date('Y'); }
$date_start_of_next_month = $year_start . '-' . $next_month . '-01 00:00:00';
if($next_month == 12) { $month_after = 1; } else { $month_after = $next_month+1; }
if($month_after == 1) { $year_end = date('Y')+1; } else { $year_end = date('Y'); }
$date_start_of_month_after_next = $year_end . '-' . $month_after . '-01 00:00:00';
Please note that instead of getting $date_end_of_next_month I chose to go with a $date_start_of_month_after_next date, it avoids the hassles with leap years and months containing different number of days.
You can simply use the >= comparaision sign for $date_start_of_next_month and the < one for $date_start_of_month_after_next.
If you prefer a timestamp format for the date, from there you will want to apply the strtotime() native function of PHP on these two variables.
You can use the php date method to find the current month and date, and then you would need to have a short list to find how many days in that month and subtract (leap year would require extra work).

Get the First or Last Friday in a Month

I'm trying to write a calendar function like this
function get_date($month, $year, $week, $day, $direction)
{
....
}
$week is a an integer (1, 2, 3...), $day is a day (Sun, Mon, ...) or number, whichever is easier. The direction is a little confusing, because it does a different calculation.
For an example, let's call
get_date(5, 2009, 1, 'Sun', 'forward');
It uses the default, and gets the first Sunday in May ie 2009-05-03. If we call
get_date(5, 2009, 2, 'Sun', 'backward');
, it returns the second last Sunday in May ie 2009-05-24.
The language-agnostic version:
To get the first particular day of the month, start with the first day of the month: yyyy-mm-01. Use whatever function is available to give a number corresponding to the day of the week. Subtract that number from the day you are looking for; for example, if the first day of the month is Wednesday (2) and you're looking for Friday (4), subtract 2 from 4, leaving 2. If the answer is negative, add 7. Finally add that to the first of the month; for my example, the first Friday would be the 3rd.
To get the last Friday of the month, find the first Friday of the next month and subtract 7 days.
Perhaps it can be made quicker...
This was VERY interesting to code.
Please note that $direction is 1 for forward and -1 for backward to ease things up :)
Also, $day begins with a value of 1 for Monday and ends at 7 for Sunday.
function get_date($month, $year, $week, $day, $direction) {
if($direction > 0)
$startday = 1;
else
$startday = date('t', mktime(0, 0, 0, $month, 1, $year));
$start = mktime(0, 0, 0, $month, $startday, $year);
$weekday = date('N', $start);
if($direction * $day >= $direction * $weekday)
$offset = -$direction * 7;
else
$offset = 0;
$offset += $direction * ($week * 7) + ($day - $weekday);
return mktime(0, 0, 0, $month, $startday + $offset, $year);
}
I've tested it with a few examples and seems to work always, be sure to double-check it though ;)
PHP's built-in time functions make this simple.
http://php.net/manual/en/function.strtotime.php
// Get first Friday of next month.
$timestamp = strtotime('first fri of next month');
// Get second to last Friday of the current month.
$timestamp = strtotime('last fri of this month -7 days');
// Format a timestamp as a human-meaningful string.
$formattedDate = date('F j, Y', strtotime('first wed of last month'));
Note that we always want to make sure that we've defined the correct timezone for use with strtotime so that PHP has an understanding of where to compute the timestamp for relative to what time zone the machine thinks it's in.
date_default_timezone_set('America/New_York');
$formattedDate = date('F j, Y', strtotime('first wed of last month +1 week'));
strtotime() can help you. e.g. <?php
$tsFirst = strtotime('2009-04-00 next friday');
$tsLast = strtotime('2009-05-01 last friday');
echo date(DATE_RFC850, $tsFirst), " | ", date(DATE_RFC850, $tsLast);printsFriday, 03-Apr-09 00:00:00 CEST | Friday, 24-Apr-09 00:00:00 CEST
No need for calculations or loops - this is very easy to do with strtotime():
Find the the Nth or Last occurrence of a particular day of a particular a month:
/////////////////////////////////////////////////////////////////
// Quick Code
/////////////////////////////////////////////////////////////////
// Convenience mapping.
$Names = array( 0=>"Sun", 1=>"Mon", 2=>"Tue", 3=>"Wed", 4=>"Thu", 5=>"Fri", 6=>"Sat" );
// Specify what we want
// In this example, the Second Monday of Next March
$tsInMonth = strtotime('March');
$Day = 1;
$Ord = 2;
// The actual calculations
$ThisMonthTS = strtotime( date("Y-m-01", $tsInMonth ) );
$NextMonthTS = strtotime( date("Y-m-01", strtotime("next month", $tsInMonth) ) );
$DateOfInterest = (-1 == $Ord)
? strtotime( "last ".$Names[$Day], $NextMonthTS )
: strtotime( $Names[$Day]." + ".($Ord-1)." weeks", $ThisMonthTS );
/////////////////////////////////////////////////////////////////
// Explanation
/////////////////////////////////////////////////////////////////
// Specify the month of which we are interested.
// You can use any timestamp inside that month, I'm using strtotime for convenience.
$tsInMonth = strtotime('March');
// The day of interest, ie: Friday.
// It can be 0=Sunday through 6=Saturday (Like 'w' from date()).
$Day = 5;
// The occurrence of this day in which we are interested.
// It can be 1, 2, 3, 4 for the first, second, third, and fourth occurrence of the day in question in the month in question.
// You can also use -1 to fine the LAST occurrence. That will return the fifth occurrence if there is one, else the 4th.
$Ord = 3;
////////////////////////////////////////////////////////////////
// We now have all the specific values we need.
// The example values above specify the 3rd friday of next march
////////////////////////////////////////////////////////////////
// We need the day name that corresponds with our day number to pass to strtotime().
// This isn't really necessary = we could just specify the string in the first place, but for date calcs, you are more likely to have the day number than the string itself, so this is convenient.
$Names = array( 0=>"Sun", 1=>"Mon", 2=>"Tue", 3=>"Wed", 4=>"Thu", 5=>"Fri", 6=>"Sat" );
// Calculate the timestamp at midnight of the first of the month in question.
// Remember $tsInMonth is any date in that month.
$ThisMonthTS = strtotime( date("Y-m-01", $tsInMonth ) );
// Calculate the timestamp at midnight of the first of the FOLLOWING month.
// This will be used if we specify -1 for last occurrence.
$NextMonthTS = strtotime( date("Y-m-01", strtotime("next month", $tsInMonth) ) );
// Now we just format the values a bit and pass them to strtotime().
// To find the 1,2,3,4th occurrence, we work from the first of the month forward.
// For the last (-1) occurence,work we work back from the first occurrence of the following month.
$DateOfInterest = (-1 == $Ord) ?
strtotime( "last ".$Names[$Day], $NextMonthTS ) : // The last occurrence of the day in this month. Calculated as "last dayname" from the first of next month, which will be the last one in this month.
strtotime( $Names[$Day]." + ".($Ord-1)." weeks", $ThisMonthTS ); // From the first of this month, move to "next dayname" which will be the first occurrence, and then move ahead a week for as many additional occurrences as you need.
echo date('Y-m-d',strtotime('last friday'));
You can use mktime to retrieve the unix timestamp of the first day in the month:
$firstOfMonth = mktime(0, 0, 0, $month, 1, $year);
When you have the date of the first day of a certain month it's easy to retrieve the weekday for that date using date:
$weekday = date("N", $firstOfMonth);
From there it's rather easy to just step forward to get the date you're after.
function get_date($month, $year, $week, $day) {
# $month, $year: current month to search in
# $week: 0=1st, 1=2nd, 2=3rd, 3=4th, -1=last
# $day: 0=mon, 1=tue, ..., 6=sun
$startday=1; $delta=0;
if ($week < 0) {
$startday = date('t', mktime(0, 0, 0, $month, 1, $year)); # 28..31
$delta=1;
}
$start = mktime(0, 0, 0, $month, $startday, $year);
$dstart = date('w', $start)-1; # last of the month falls on 0=mon,6=sun
$offset=$day-$dstart; if ($offset<$delta){$offset+=7;}
$newday=$startday+$offset+($week*7);
return mktime(0, 0, 0, $month, $newday, $year);
}
This works for me, and based on the language-agnostic version :-)
Only too bad, I needed to do that delta-thing (for if the last day of the month is the wanted week-day, we do not need to subtract 7)
The same can be accomplished very elegantly using the DateTime class.
$time_zone = new DateTimeZone('Europe/Ljubljana');
$first_friday_of_this_month = new DateTime('first Friday of this month', $time_zone);
$last_friday_of_this_month = new DateTime('last Friday of this month', $time_zone);
echo $first_friday_of_this_month->format('Y-m-d'); # 2015-11-06
echo $last_friday_of_this_month->format('Y-m-d'); # 2015-11-27
Just find out what the first and last day of the month in question is (i.e. May 1, 2009 is a Friday and May 31, 2009 is a Sunday) I believe most PHP functions use Monday=0, Sunday=6, thus Friday=4, so you know that Sunday (6) - Friday (4) = 2, then 31-2 = 29, meaning the last friday of this month is on the 29th. For the first Friday, if the number is negative, add 7, if the number is 0, the month starts on Friday.
This seems to work perfect everytime; it takes any date provided and returns the date of the last friday of the month, even in case of 5 friday in the month.
function get_last_friday_of_month($inDate) {
$inDate = date('Y-m-24', strtotime($inDate));
$last_friday = date('Y-m-d',strtotime($inDate.' next friday'));
$next_friday = date('Y-m-d',strtotime($inDate.' next friday'));
if(date('m', strtotime($last_friday)) === date('m', strtotime($next_friday))){
$last_friday = $next_friday;
}else{
//
}
return $last_friday;
}
Below is the quickest solution and you can use in all conditions. Also you could get an array of all day of week if you tweak it a bit.
function findDate($date, $week, $weekday){
# $date is the date we are using to get the month and year which should be a datetime object
# $week can be: 0 for first, 1 for second, 2 for third, 3 for fourth and -1 for last
# $weekday can be: 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday, 6 for Saturday and 7 for Sunday
$start = clone $date;
$finish = clone $date;
$start->modify('first day of this month');
$finish->modify('last day of this month');
$finish->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $finish);
foreach($period AS $date){
$result[$date->format('N')][] = $date;
}
if($week == -1)
return end($result[$weekday]);
else
return $result[$weekday][$week];
}
$date = DateTime::createFromFormat('d/m/Y', '25/12/2016');
# find the third Wednesday in December 2016
$result = findDate($date, 2, 3);
echo $result->format('d/m/Y');
I hope this helps.
Let me know if you need any further info. ;)

Categories