How can i get the previous 6months in codeigniter(php)? - php

I'm making a billing page.
In here, i have to get the latest 6 year-month based on the current month.
For example,
if i use,
date('Ym')
i get 201308
and if i use,
date('Ym')-1
i get 201307
ok, fine! But the problem is,
what if the current month is 201301?
in this situation if i do
date('Ym')-1
I get 201300, but i need 201212.
Any good idea?

Don't use date() for this. It wasn't made for it. Use DateTime() instead.
$dt = new DateTime();
$dt->modify('-1 month');
echo $dt->format('Ym');
See it in action
Or
$dt = new DateTime();
$dt->sub(new DateInterval('P1M'));
echo $dt->format('Ym');
See it in action

Related

DateTime::createFromFormat doesn't work properly with format 2017-02

I have a following code, which would returns me previous and next date (selection by months). But I found it not working properly, when user selects a february. This is my code, which is applied to get the dates:
$dateSelect = #$_GET['datum'] ?: date('Y-m');
$date = DateTime::createFromFormat('Y-m', $dateSelect);
$prevdate = clone $date;
$date->modify('first day of next month');
$this->view->next_month = $date->format('m');
$this->view->next_year = $date->format('Y');
$prevdate->modify('first day of previous month');
$this->view->prev_month = $prevdate->format('m');
$this->view->prev_year = $prevdate->format('Y');
I have made an example so you can test it faster: PHP Sandbox
If user selects date 2017-02 then it is processed as 2017-03, which is incorrect. Try changing the value to 2017-01 in the example and you will see it is working properly. Since buttons in my code are filling with these values, my users can't go before February 2017 without manually changing the URL.
As DateTime will populate the missing d part of the date based on the current date, you're effectively getting 2017-02-29 (given that today is the 29th), which isn't valid, but DateTime adjusts to a valid date by rolling forward into the following month, giving 2017-03-01.
You need to force a d part to the date to avoid this default behaviour
$date = DateTime::createFromFormat('Y-m-d', $dateSelect . '-01');

strtotime every refresh minutes and seconds change why

$order_startdate = date('Y-m-d H:i:s'); // current date & time
$NewDate=Date('Y-m-d H:i:s', strtotime("+3 days", strtotime($order_startdate))); // 3 days increase Date And Time also
var_dump($NewDate);
I am get string(19) 2015-06-29 06:56:42
after refresh it has changed 2015-06-29 07:03:19
I want the time do not changed time i want
$NewDate I'm Used in NextPayment Date in Subscription Payment
For Now
i am in struggle !
Thanks
You are creating a new Date() instance every time the script loads, which means that every time you refresh the page new time value is returned because of the nature of time (it changes over time :D)
If you want to save the time, that means, you need to write the value of your variable when it is created into database/somewhere else.
Following from #Slim Kallari's answer, you could do this, to get a new date only when one is not already set:
if(!isset($_SESSION['NewDate']))
{
$NewDate=Date('Y-m-d H:i:s', strtotime("+3 days", strtotime($order_startdate)));
$_SESSION['NewDate'] = $NewDate;
}
else
{
$NewDate= $_SESSION['NewDate'];
}
var_dump($NewDate);
That way, you create a new Date instance if one doesn't already exists. Make sure to add session_start(); before creating your session variable, though.
Finally I research myself and implemented as working solution finally here it is best instead of dom just remove dom and try it should did a trick
$date = $order->order_date;// checkout placeorder date
$trial = '1';
$subsc = date('Y-m-d H:i:s', strtotime($date. '+ '. $trial . 'days'));

PHP: DateTime '-1 day'

I want to get the date of yesterday of the current date in a specifc time zone.
I tried like this, but it is not working:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$yesterday = $date->modify( '-1 day' );
$yesterday = $yesterday->format('Y-m-d');
I am still getting today's date.
This problem, according to the documentation for the modify() method, seems to entirely depend on which version of php you're using. In this case, method chaining(which is what you're attempting to do is called), is only available on php version 5.3.0 and up, according to the changelog on the previously linked docs.
That in mind, it explains why your code didn't work, and #Deryck's did. If you ever do upgrade your php version, or get your host to upgrade it, you could likely reduce those three lines to two:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date = $date->modify( '-1 day' )->format('Y-m-d');
Not much of an improvement, I realize, but there's your reason for why it failed to work.
Below are two of the methods I see of getting around this; one is creation of a class.. which seems like overkill to me unless this is apart of something grander... the other is a creation of a function. Both shove the extra lines into something that takes up less space, in a sense.
class DT {
private $now; //can be null
private $timezone; //DateTimeZone object
public function __construct($tz_str, $now = NULL) {
$this->now = $now;
$this->timezone = new DateTimeZone($tz_str);;
}
public function mod($mod,$format) {
$dt = new DateTime($this->now, $this->timezone);
$dt->modify($mod);
return $dt->format($format);
}
}
function mod_formatted_zone($tz_str, $mod, $format, $now = NULL) {
$timezone = new DateTimeZone($tz_str);
$dt = new DateTime($now,$timezone);
$dt->modify($mod);
return $dt->format($format);
}
The use of either is simple; in the case of the class, it'd be something like..
$dt = new DT('Pacific/Wake');
echo $dt->mod('-1 day', 'Y-m-d');
While in the case of the function, it'd simply be..
echo mod_formatted_zone('Pacific/Wake', '-1 day', 'Y-m-d');
Seems to work once you don't re-assign the $date variable unnecessarily. See below:
<?php
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date->modify("-1 day");
$date = $date->format("Y-m-d");
// echo $date; // just in case you wanna echo - ya dig
?>
View demo
FYI:
Wake Island Time Zone (UTC+12:00)
Which means 1 day before is actually today (for me at least, on the western hemisphere).
I want to get the date of yesterday of the current date in a specifc time zone.
You can specify relative dates in the DateTime constructor. This will work for you:-
$yesterday = new DateTime('- 1 day', new DateTimeZone('Pacific/Wake'));
var_dump($yesterday);
Proof!.

How to extend date in PHP?

I have developed a subscription website. I am facing php date extend problem.
Please read my message-
Suppose today i have subscribe a package. Package duration 1 month. I mean 2014-05-08 to 2014-06-07
After two days i will again subscribe this same package. now the Package duration will extend 2014-06-07 to 2014-07-07
In my PHP code i am getting current date to +1 month but how to get after 1 month to next one month?
I have used this code:
date('Y-m-d h:i:s', mktime(0, 0, 0, date("m")+$getSubscription['Subscription']['duration'], date("d"), date("Y")));
You can use strtotime to achieve this.
Check this out:
<?php
// current subscription expiry date
$day = '2014-06-07';
// add 30 days to the date above
$new_date = date('Y-m-d', strtotime($day . " +30 days"));
// debug
echo $new_date;
Outputs: 2014-07-07
P.s. are you saving the newly calculated date into db or something and then using it on the next calculation?
Or use the DateTime object :
<?php
$date = new DateTime('2014-06-07');
$date_end = clone $date;
$date_end->add(new DateInterval('P1M');
echo $date_end->format('Y-m-d');
You'd save yourself a lot of hassle by using DateTime objects instead of messing around with date() and mktime(). In order to get today, simply:
$subscriptionDate = new DateTime(); // 2014-05-08
Then you can use the DateInterval class to add additional months, so if it's a monthly subscription, simply:
$subscriptionPeriod = new DateInterval('P1M');
$subscriptionDate->add($subscriptionPeriod);
Now, $subscriptionDate will be at 2014-06-08. You can keep adding as many months as you want and save it to your database, in the format you want, like:
$subscriptionDate->format('Y-m-d'); // 2014-06-08
$subscriptionDate->format('Y-m-d H:i:s'); // incl. time, e.g. 2014-06-08 12:02:45
See the manual for more examples.

Convert date into timestamp where strtotime has already been used

I' am trying to convert the date of next 7 days into timestamp so that I can compare against my date timestamp in database to get some results.
This function is used to get the next 7 days from today
$next_date = date("d/m/Y", strtotime("7 day"))
Output
30/04/2014
Now I' am again running strtotime() on $next_date variable who holds the next 7days and converting to timestamp.
echo strtotime($next_date);
This is not working. I followed this stackoverflow answer and few others.
As an alternative suggestion you could look at PHP's internal DateTime() and DateInterval() classes. It makes it a bit easier to convert between formats and do date/time addition and subtraction imho. DateInterval requires at least PHP version 5.3.
An example:
// create a current DateTime
$currDate = new DateTime();
// copy the current DateTime and
// add an interval of 7 days
$nextDate = clone $currDate;
$nextDate->add(new DateInterval('P7D'));
// both objects are easily converted to timestamps
echo $currDate->getTimestamp(); // e.g: 1398296728
echo $nextDate->getTimestamp(); // e.g: 1398901528
// and both can be easily formatted in other formats
echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
EDIT
For completeness, here's another example of how you can add seven days to a DateTime object:
$now = new DateTimeImmutable();
$then = $now->modify('+7 days');
var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
Yields:
string(10) "2016-05-24"
string(10) "2016-05-31"
You can also use DateTime - the difference in this use case is that DateTime::modify() will modify the instance $now where DateTimeImmutable::modify() will return a new DateTimeImmutable object - so if you need to create a new object whilst retaining the old one, it's probably the most succinct approach.
Hope this helps :)
http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/dateinterval.construct.php
Just store the value from strtotime first?
$timestamp_in_7_days = strtotime('7 day');
$next_date = date('d/m/Y', $timestamp_in_7_days);
There is no need to throw the time back and forth between unix timestamp and date-format.

Categories