Exact date calculator - php

Is there a way of calculating the EXACT date after/before 6 months in Php taking into consideration the dynamic change in the days of the month i.e. consider some months have 30 days and some have 31 and 28 of course. I know it can be done with MySQL but I want to know if there is an option with Php as well.
Thanks in advance.

you need to date_create, date_interval_create_from_date_string and date_format to complete the job.
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('6 months'));
echo date_format($date, 'Y-m-d'); // 2000-07-01
With Object Oriented:
Adding
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P6M'));
echo $date->format('Y-m-d') . "\n"; // 2000-07-01
Subtracting
$date = new DateTime('2000-01-01');
$date->sub(new DateInterval('P6M'));
echo $date->format('Y-m-d') . "\n"; // 1999-07-01

get date before 6 month from current month:
echo date("F 1, Y", strtotime("-6 months"));

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

How to add months to a particular date

I just hope this question won't be marked as a duplicate because I've seen similar questions on stackoverflow but they all talk about adding days to the date, The problem here is that i want to add some particular months to a particular date which is gotten from my database I've tried adding it using strtotime() but the date just returns 1st January 1970, the code looks like this
<?php echo date('jS F Y', strtotime("$date +1 month")); ?>
//This is the value of date
$date = $student->date;
How to I add months to this particular date? Please note that the date is a timestamp in my database.Thanks
You have a Unix timestamp, not an actual date. Here I use the DateTime class to create a datetime object using that Unix timestamp. Then I can add a month to it and format the output.
$date = new DateTime('#'.$student->date);
$date->modify('+1 month');
echo $date-format('jS F Y');
If you want to stick to using date() and strtotime() you would use this:
echo date("jS F Y", strtotime("+1 month", $student->date));
strtotime() would take the starting date as the second parameter and then how you wish to modify it as your first parameter.
You should check out the documentation here,
But the just of it is the $date->add function. It allows you to add any amount of time to a timestamp using a DateInterval. Its a little tricky to get used to but here are a couple of examples:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
which outputs:
2000-01-01 10:00:30
2007-06-05 04:03:02
The date interval is formatted in years months days hours minuets seconds, simply put in the amount you want and it will add it, so in your case:
<?php
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
PHP's strtotime() function allows for a second parameter that allows you to set a relative date.
If you would like to add a month to tomorrow, here's how:
<?php
echo date("jS F Y", strtotime("+1 month", strtotime("2014-10-09")));
// returns: 9th November 2014

Get 30 days back date along with time

I want to calculate EXACT past 30 days time period in php from now (for example 30 aug 14 23:06) to 30 days back (for example 1 aug 14 23:06). I wrote this where current datetime goes in $d1 and past 30 days datetime goes in $d2 but somehow i am not getting correct results. Any idea?
$url=$row["url"];
$pageid=getPageID($url);
$date=date('y-m-d g:i');
$d1=strtotime($date);
$d2=date(strtotime('today - 30 days'));
Thanks
The problem is likely caused by the malformed date() call. The first argument passed to date() should be the format (as shown in the Docs) and the second should be an optional timestamp.
Try this:
$d2 = date('c', strtotime('-30 days'));
PHPFiddle
As a short aside, the whole snippet can be simplified as follows:
$url = $row["url"];
$pageid = getPageID($url);
$date = date('y-m-d g:i');
$d1 = time();
$d2 = date('y-m-d g:i', strtotime('-30 days'));
You can also use the DateTime class's sub() method together with an DateInterval:
$now = new DateTime();
$back = $now->sub(DateInterval::createFromDateString('30 days'));
echo $back->format('y-m-d g:i');
if you would like to get out put as 2014-08-01 then try the below code. thanks
$date = '2014-08-30 23:06';
$new_date = date('Y-m-d G:i', strtotime($date.' - 29 days'));
echo "30 days back is " . $new_date;
From your brief description and example given, I believe that you want the date to be 30 days back and time to be the same as of now. The below code will serve this purpose. Thanks.
<?php
$date=date('y-m-d g:i');
$time=date('g:i');
echo "Todays date:" . $date. "<br>";
$d2 = date('y-m-d', strtotime('-30 days'));
echo "30 days back:" . $d2 . ' ' .$time;
?>
Try:
echo date("Y-m-d h:i:s",strtotime('-30 days'));
For more detail click here
Very simple two lines of code
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
I know you said with PHP, however, I can't imagine not getting the records from a DB. If you want to do so from the DB,use:
$sql='SELECT * FROM myTable WHERE date > CURRENT_DATE - INTERVAL 30 DAY';
$pdo->query($sql);
Very simple one lines of code:
echo (new DateTime())->modify('-30 day')->format('y-m-d g:i');
In the example below, it makes no sense if the variable $date is not
used anywhere else!
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
Sample answer is
$dateBack30Days=date('Y-m-d g:i', strtotime('-30 days'));

Adding Days to a Date with PHP

I am trying to add a certain amount of days to a set date in PHP. However, all of the code I use is not working. Here is the code I am currently experiencing problems with:
echo date("2013-12-01", strtotime("+7 days"));
I wanting to add 7 days to the date above. When I echo out this code, it just prints '2013-12-01'. Is there a way to do this?
Thanks
For the sake of completeness, here's how you do it with DateTime():
$datetime = new DateTime("2013-12-01");
$datetime->add(new DateInterval('P7D'));
echo $datetime->format('Y-m-d');
or
$datetime = new DateTime("2013-12-01");
$datetime->modify('+7 days');
echo $datetime->format('Y-m-d');
You can use date_add() function:
$date = date_create('2013-12-01');
date_add($date, date_interval_create_from_date_string('7 days'));
echo date_format($date, 'Y-m-d');
This will output 2013-12-08
It must be like this:
$NewDate = date('Y-m-d', strtotime("2013-12-01" . " +7 days"));
echo $NewDate;

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