Decrease month by one in strtotime? - php

all
Decrease month by one in strtotime in this loop.
$twitter_val7 .='{
date: new Date('.date("Y",strtotime($date)).', '.date("m",strtotime($date)).', '.date("d",strtotime($date)).'),
value: '.$result_twitter->counts.'
},';

To decrease by 1 month using strtotime() you literally tell it to decrease by one month:
strtotime($date . ' - 1 month');
Assuming, of course, that $date is a format strtotime() understands.

I would do it like this .. i guess $date would go in place of '2000-01-01':
$initial = new DateTime('2000-01-01');
$interval = new DateInterval('P1M');
$newdate = $initial->sub( $interval );
echo $newdate->format('Y-m-d H:i:s');

To decrease month by using strtotime
$date='2014-09-03';
$numMonth=1;//here you can pass no. of month
$resultDate=date('Y-m-d',strtotime($date . " - $numMonth month"));

Related

PHP datetime add 6 months and 1 year

I have a date set using PHP datetime like this..
$originaldate = 2019-01-10 17:52:17
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
The date is successfuly converted into a PHP DateTime object, now I am trying to add create 2 new dates that are 6 months and 1 year ahead of this date.
Whats the best way to achieve this?
You should look into php class DateInterval http://php.net/manual/en/class.dateinterval.php
Here's an example:
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));//add one year //object reference is the same so adding a year altered original object and a reference to it is passed back, not copied
$converted2 = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted6months = $converted2->add(new DateInterval("P6M")); // add 6 months
And as suggested in the comments here's the DateTimeImmutable equivalent:
$converted = DateTimeImmutable::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));
$converted6Months = $converted->add(new DateInterval("P6M"));
Check out DateTime::add
$converted->add(new DateInterval("P18M")); // add 18 months
P18M means 18 month interval
You can clone the time to create a duplicate and use DateTime::modify to change the new date.
Try this;
$sixMonths = clone $converted;
$sixMonths->modify('+6 months');
$oneYear = clone $converted;
$oneYear->modify('+1 year');
$converted = $converted->modify('+6 months');
$converted = $converted->modify('+1 year');
Like so:
$sixMonths = date('Y-m-d', strtotime($converted. ' + 6 months'));
$oneYear = date('Y-m-d', strtotime($converted. ' + 1 year'));
The format already default ("Y-m-d H:i:s"). You don't need to use CreateFromFormat, unless you are handle data from 3rd party. My suggestion for the code would be like this
$originaldate = '2019-01-10 17:52:17';
$converted = new DateTime( $originaldate ); //prefer like this
//DateTime::createFromFormat("Y-m-d H:i:s", $originaldate); //after browsing this is recomended
$date6Month = new DateTime( $originaldate );
$date1Year = new DateTime( $originaldate );
$dateBack = new DateTime( $originaldate );
//$date6Month = $date1Year = $dateBack= $converted;
//prefer to use different variable for every date. Not copy
echo "ori:".$converted ->format('Y-m-d H:i:s') . "\n";
//ori:2019-01-10 17:52:17
##6 month later
$date6Month ->add(new DateInterval('P6M'));
echo "6 month:".$date6Month ->format('Y-m-d H:i:s') . "\n";
//6 month:2019-07-10 17:52:17
##1 year later
$date1Year ->add(new DateInterval('P1Y'));
echo "1 year:".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year:2020-01-10 17:52:17
//1 year:2020-07-10 17:52:17 (wrong if using copy main parameter)
$date1Year ->add( DateInterval::createFromDateString('1 Years') );
echo "1 year (later):".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year (later):2021-01-10 17:52:17
//1 year (later):2021-07-10 17:52:17 (wrong if using copy main parameter)
you can use DateInterval::createFromDateString for readable code than using format. My suggestion is to separated the variable not copy from the origin.
The format you can use on DateInterval
Start "P" when contain Day, Month and Year
Format
Info
Example
Y
Year
1Y
M
Month
3M
D
Day
5D
example: P1Y3M5D
Always Start "P" before "T" if not contain Day, Month and Year (PT1H). If not start it with "T"
Format
Info
Example
H
HOUR
1H
M
MINUTES
3M
S
SECONDS
5S
F
MICROSECOND (php7+)
5F
example: PT1H3M5S
wrong: T1H3M5S
other example (from link below)
date_default_timezone_set('America/Phoenix');
//is important to add when your time are detail
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
//2007-06-05 04:03:02
$originaldate = 2019-01-10 17:52:17
$dateBack = $dateBack2 = new DateTime( $originaldate );
//if you want to substract the value you can use this
$dateBack ->sub(new DateInterval('P1Y2M3DT1H4M1S'));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//output: 2019-05-07 16:48:16
$dateBack2=$converted;
$formatDay='P1Y3M6D'; //only year, month and day
$formatTime='T1H3M6S'; //only hour, minutes and seconds
$dateBack2 ->sub(new DateInterval( $formatDay.$formatTime ));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//2018-02-01 15:45:10
as mention on the phpmanual, there is other format (microtime) that's not include on this example.
related link
Date Time PHP
Date Interval
Format on Interval
Date Interval create using String

Find next occurrence of date

I want to find the next occurrence of date from the current date.
For example, imagine I want to find 20th of the month from current date
If current date is 10th october then return the result 2014-10-20 (Y-m-d)
If current date is 22nd october then return the result 2014-11-20 (Y-m-d)
I created a solution just now using a while loop.
$oldd= "2014-06-20";
$newdate = date("Y-m-d",strtotime($oldd."+1months"));
while(strtotime($newdate) <= strtotime(date("Y-m-d")))
{
$newdate = date("Y-m-d",strtotime($newdate."+1months"));
}
echo $newdate;
manually and pass that to strtotime(). The time information you need to extract from the reference time string. Like this:
$refdate = '2014-02-25 10:30:00';
$timestamp = strtotime($refdate);
echo date('Y-m-d H:i:s',
strtotime("next Thursday " . date('H:i:s', $timestamp), $timestamp)
);
same results could be achieved using string concatenation:
echo date('Y-m-d', strtotime("next Thursday", $timestamp)
. ' ' . date('H:i:s', $timestamp);
another way, you can use methods of DateTime object, PHP has really rich API in dealing with date time.
$current_date = new DateTime('2014-06-20');
if ($current_date->format('d') >= 20) {
// $current_date->modify('last day of this month')->modify("+20 days");
$current_date->modify('first day of next month')->modify("+19 days");
}else{
$current_date->modify('first day of this month')->modify("+19 days");
}
echo $current_date->format("Y-m-d");
http://php.net/manual/en/datetime.modify.php
http://php.net/manual/en/datetime.formats.relative.php

PHP: Incorrect strtotime()

I had gone through various stackoverflow solutions and other blogs but still it doesn't fix my problem.
Let's say that the date today is: 2013-12-28 and I want to get the date after 1 month and it is supposed to display 2014-01-28.
$date = date('o-m-d');
$final = date('o-m-d', strtotime("+1 month", $date));
echo $final;
Above is my code. It returns 02/01/1970.
I have also tried the mktime method but still it displays the 1970 output.
What am I doing wrong?
BTW. I am working this on a hosted server.
Thanks ahead. :)
Use DateTime function modify
$date = new DateTime( 'o-m-d' );
echo $date->modify( '+1 month' )->format('o-m-d');
If you want the current date +1 month use:
$final = date('o-m-d', strtotime("+1 month"));
Or with a given date:
$date = date('o-m-d');
$final = date('o-m-d', strtotime($date . " +1 month"));
echo $final;
If you want to use the second parameter of strtotime it has to be a timestamp.
Go the OOP way..
<?php
$date = new DateTime('2013-12-28');
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d'); //prints 2014-01-28

Need to find future date using PHP

I need to find future date using php.But using php, I am unable to get correct date for February.I posted my code below.I need end date of February.Thanks in advance.
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . " +2 month");
$end_date=date("Y-m-d",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
You can use the 1st of March and subtract 1 day:
$date = date_create('2012-03-01');
$date->modify("-1 day");
echo $date->format("Y-m-d");
Try this code.
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-t", strtotime($date)) . " +2 month");
$end_date=date("Y-m-t",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
If you absolutely need to use strtotime, you could try with this:
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . ", next month, last day of next month");
$end_date=date("Y-m-d",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
Which will return what you expect: 2012-02-29.
You can take a look at relative formats for strtotime in the PHP Manual as well.
$dt = new DateTime();
$dt->setDate(2011, 12, 31);
$dt->modify('last day of +2 month');
//or
$dt->modify('+2 month -2 day');
//or
$dt->modify('next month last day of next month');
print_r ($dt);
use the below code to find the first/last day of a given month,
<?php
function findFirstAndLastDay($anyDate)
{
//$anyDate = '2009-08-25'; // date format should be yyyy-mm-dd
list($yr,$mn,$dt) = split('-',$anyDate); // separate year, month and date
$timeStamp = mktime(0,0,0,$mn,1,$yr); //Create time stamp of the first day from the give date.
$firstDay = date('D',$timeStamp); //get first day of the given month
list($y,$m,$t) = split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
$lastDayTimeStamp = mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
$lastDay = date('D',$lastDayTimeStamp);// Find last day of the month
$arrDay = array("$firstDay","$lastDay"); // return the result in an array format.
return $arrDay;
}
//Usage
$dayArray=array();
$dayArray=findFirstAndLastDay('2009-02-25');
print $dayArray[0];
print $dayArray[1];
?>
<?php
$date = '2011-12-31';
$tmp_date = strtotime(date("Y-m-1", strtotime($date)) . " +2 month");
$end_date=date("Y-m-t",$tmp_date);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$date = '2011-12-31';
$end_date = new DateTime($date);
$end_date->modify('last day of +2 month');
echo $end_date->format('Y-m-d');
Live Demo
OR
Use strtotime()
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . ", last day of +2 month");
echo $end_date = date("Y-m-d",$dateOneMonthAdded);

Given a time, how can I find the time one month ago

Given a time, how can I find the time one month ago.
strtotime( '-1 month', $timestamp );
http://php.net/manual/en/function.strtotime.php
In php you can use strtotime("-1 month"). Check out the documentation here: http://ca3.php.net/strtotime
We can achieve same by using PHP's modern date handling. This will require PHP 5.2 or better.
// say its "2015-11-17 03:27:22"
$dtTm = new DateTime('-1 MONTH', new DateTimeZone('America/Los_Angeles')); // first argument uses strtotime parsing
echo $dtTm->format('Y-m-d H:i:s'); // "2015-10-17 03:27:22"
Hope this adds some more info for this question.
<?php
$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';
date_sub($date, new DateInterval("P1M"));
echo '<br />'.$date->format("d-m-Y").' : 1 Month';
?>
PHP 5.2=<
$date = new DateTime(); // Return Datetime object for current time
$date->modify('-1 month'); // Modify to deduct a month (Also can use '+1 day', '-2 day', ..etc)
echo $date->format('Y-m-d'); // To set the format
Ref: http://php.net/manual/en/datetime.modify.php
This code is for getting 1 month before not 30 days
$date = "2016-03-31";
$days = date("t", strtotime($date));
echo date("Y-m-d", strtotime( "-$days days", strtotime($date) ));
These answers were driving me nuts. You can't subtract 31 days and have a sane result without skipping short months.
I'm presuming you only care about the month, not the day of the month, for a case like filtering/grouping things by year and month.
I do something like this:
$current_ym = date('ym',strtotime("-15 days",$ts));

Categories