Is there a way to find the day of the week in php with a particular date.
I don't mean
date('D', $timestamp);
I mean if I was to supply a date like 2010-10-21 it would return "third thursday".
Not directly, you need a helper function for that:
function literalDate($timestamp) {
$timestamp = is_numeric($timestamp) ? $timestamp : strtotime($timestamp);
$weekday = date('l', $timestamp);
$month = date('M', $timestamp);
$ord = 0;
while(date('M', ($timestamp = strtotime('-1 week', $timestamp))) == $month) {
$ord++;
}
$lit = array('first', 'second', 'third', 'fourth', 'fifth');
return strtolower($lit[$ord].' '.$weekday);
}
echo literalDate('2010-10-21'); // outputs "third thursday"
Working example:
http://codepad.org/PTWUocx9
strtotime() seems to understand the syntax. You just need to provide it with the first day of the month in question as a starting point.
echo date("d.m.Y", strtotime("third thursday", mktime(0,0,0,10,1,2010)));
// Will output October 21
echo date("d.m.Y", strtotime("third thursday", mktime(0,0,0,11,1,2010)));
// Will output November 18
Related
I'd like to calculate next billing date of Recurly plan in PHP.
There are 2 types of billing cycle: yearly | monthly.
I tried to use DateTime and DateInterval classes, but didn't get expected results.
<?php
$referenceTime = new \DateTime('2016-01-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-03-02 00:00:00.000000'
Adding one month to the 31st of Januray gives me the second of March and not the 29th (or 28th) of February as I would expect.
The same for the 31st of August:
<?php
$referenceTime = new \DateTime('2016-08-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-10-01 00:00:00.000000'
If yearly, I expect Feb 29, 2016 + 1 year => Feb 28, 2017
Thanks.
Try this, if date > 28 use last day of next month else use +1 month
$get_date = strtotime("31-01-2016");
$dt = explode("-",$get_date);
$dt = $dt[0];
var_dump(($dt > 28) ? date("d-m-Y", strtotime("31-01-2016 last day of next month")) : date("d-m-Y", strtotime("31-01-2016 +1 month")));
DEMO
You can call modify with PHP's DateTime object to calculate the next date relative to the current date. The following code shows how you would do it with your specific situation.
$next_bill_date = new DateTime();
switch($plan_interval_unit) {
case "year":
$next_bill_date->modify("last day of next month");
break;
case "month":
$next_bill_date->modify("last day of this month next year");
break;
}
May be something like that:
if (date('d') !== date('d', strtotime('+1 month'))
date ('Y-m-d H:i:s', strtotime('last day of next month'));
if (date('d') !== date('d', strtotime('+1 year'))
date ('Y-m-d H:i:s', strtotime('last day of this month next year'));
You can use PHP inbuilt strtotime() function
// One month from today
$date = date('Y-m-d', strtotime('+1 month'));
// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2016-12-06')));
function get_next_billing_date($now, $type, $format = 'Y-m-d')
{
$date = new DateTime($now);
$y = $date->format("Y");
$m = $date->format("m");
$d = $date->format("d");
if ($type == 'year') {
$y++;
if ($m == 2 && $d == 29) {
$d = 28;
}
} else if ($type == 'month') {
if ($m == 12) {
$y++;
$m = 1;
} else {
$m++;
}
$first_date = sprintf("%04d-%02d-01", $y, $m);
$last_day_of_next_month = date('t', strtotime($first_date));
if ($d > $last_day_of_next_month) {
$d = $last_day_of_next_month;
}
} else {
// not supported
return false;
}
$date->setDate($y, $m, $d);
return $date->format($format);
}
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;
}
What I Require
I have a certain list of datetimes. I want to get the first monday of each datetimes.
eg: Suppose the given datetimes are
2013-07-05 2013-08-05, 2013-09-13 etc.
I want to get the first monday of all these datetimes such that the output results in
2013-07-01, 2013-08-05, 2013-09-02 respectively
I am actually stuck with this using stftime.
strftime("%d/%m/%Y", strtotime("first Monday of July 2012"));
Using php Datetime class:
$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
$test = new DateTime($Date);
echo $test->modify('first monday')->format('Y-m-d');
}
<?php
function find_the_first_monday($date)
{
$time = strtotime($date);
$year = date('Y', $time);
$month = date('m', $time);
for($day = 1; $day <= 31; $day++)
{
$time = mktime(0, 0, 0, $month, $day, $year);
if (date('N', $time) == 1)
{
return date('Y-m-d', $time);
}
}
}
echo find_the_first_monday('2013-07-05'), "\n";
echo find_the_first_monday('2013-08-05'), "\n";
echo find_the_first_monday('2013-09-13'), "\n";
// output:
// 2013-07-01
// 2013-08-05
// 2013-09-02
the first monday would be within the first 7 days of a month,
DAYOFWEEK(date) returns 1=sunday, 2=monday, and so on
also see the hack#23
http://oreilly.com/catalog/sqlhks/chapter/ch04.pdf
I know this is an old question and my answer is not 100% solution for this question, but this might be usefull for someone, this will give "first Saturday of the given year/month":
date("Y-m-d", strtotime("First Saturday of 2021-08")); // gives: 2021-08-07
You can manipulate this in many ways.
obviously you can put "Second Saturday of year-month" and it will find that as well.
Works with PHP 5.3.0 and above (tested at https://sandbox.onlinephpfunctions.com/).
You could loop through the array of dates and then break out of the loop and return the $Date when you first encounter Monday
PHPFIDDLE
$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
$weekday = date('l', strtotime($Date));
if($weekday == 'Monday') {
echo "First Monday in list is - " . $Date;
break;
}
}
Output
First Monday in list is - 2013-08-05
i have one date.
example : $date='2011-21-12';
data format :yyyy-dd-mm;
IF date is Saturday or Sunday.
if Saturday add 2 day to the given date.
if Sunday add 1 day to the given date.
?
In a single line of code:
if (date('N', $date) > 5) $nextweekday = date('Y-m-d', strtotime("next Monday", $date));
If the day of week has a value greater than 5 (Monday = 1, Sat is 6 and Sun is 7) set $nextweekday to the YYYY-MM-DD value of the following Monday.
Editing to add, because the date format may not be accepted, you would need to reformat the date first. Add the following lines above my code:
$pieces = explode('-', $date);
$date = $pieces[0].'-'.$pieces[2].'-'.$pieces[1];
This will put the date in Y-m-d order so that strtotime can recognize it.
You can use the date and strtotime functions for this, like so:
$date = strtotime('2011-12-21');
$is_saturday = date('l', $date) == 'Saturday';
$is_sunday = date('l', $date) == 'Sunday';
if($is_saturday) {
$date = strtotime('+2 days', $date);
} else if($is_sunday) {
$date = strtotime('+1 days', $date);
}
echo 'Date is now ' . date('Y-m-d H:i:s', $date);
What about this:
$date='2011-21-12';
if (date("D", strtotime($date)) == "Sat"){
$new_date = date("Y-m-d", strtotime("+ 2 days",$date);
}
else if (date("D", strtotime($date)) == "Sun"){
$new_date = date("Y-m-d", strtotime("+ 1 day",$date);
}
The DateTime object can be really helpful for anything like this.
In this case.
$date = DateTime::createFromFormat('Y-d-m', '2011-21-12');
if ($date->format('l') == 'Sunday')
$date->modify('+1 day');
elseif ($date->format('l') == 'Saturday')
$date->modify('+2 days');
If you want to get the date back in that format.
$date = $date->format('Y-d-m');
$date = '2011-21-12'
$stamp = strtotime($date);
$day = date("l", $stamp);
if ($day == "Saturday"){
$stamp = $stamp + (2*+86400);
}elseif($day == "Sunday"){
$stamp = $stamp + 86400;
}
echo date("Y-d-m", $stamp);
The only reason i can think why this wouldnt work is strtotime not recognising that data format...
For sundays date('w',$date) will return 0, so the simplest test code is:
if(!date('w',strtotime($date)) { ... } //sunday
I just subtracted the difference from 8 an added it to the days.
if(date('N', strtotime($date)) >= 6) {
$n = (8 - date("N",strtotime($date)));
$date = date("Y-m-d", strtotime("+".$n." days");
}
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)