How to extend date in PHP? - 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.

Related

yii2 pick time from datetime

I want to know how to pick the time format from datetime in yii2.
So if there is code like this
$model->date = date('Y-m-d H:i:s', strtotime('+5 hours'));
and the result would be 2018-05-08 23:36:21
how can I extract the time only? so the result is only 23:36:21
I already tried using code below
date("H:i:s", strtotime('-30 minutes'));
but I only got like 00:30:00
Is there something wrong with the code?
Any help would be appreciated :)
if you have the string 2018-05-08 23:36:21 and want to extract time, you can follow the following methods
Using php:date() function
Remove -30m from the time when you format the date
echo date('H:i:s',strtotime('2018-05-08 23:36:21 -30 minutes'));
Using DateTime Object
The method sub() can subtract from the time and output the remaining time using $dateTimeObj->format().
$date1=new \DateTime('2018-05-08 23:36:21');
$date1->sub(new \DateInterval('PT30M'));
echo $date1->format('H:i:s');

Next delivery date listed on website

I'm building a website for a business that makes deliveries every second Thursday. I need to display when the next delivery is going to be, and have that date change to two weeks forward when the previous delivery date is reached.
Based on what I've been able to research so far, I've cobbled together this code:
$start_date = '2016-10-27'; // next delivery date to start counting from
// create a DateTime object that represents start of sequence
$start_datetime = DateTime::createFromFormat('Y-m-d', $start_date);
// create a DateTime object representing the current date
$current_datetime = new DateTime('today');
$date_interval = new DateInterval('P2W'); // for delivery every 2 weeks
// determine end date for DatePeriod object that will later be used
// this is no further out than current date plus the interval
$end_datetime = new DateTime('tomorrow');
$end_datetime->add($date_interval);
$date_period = new DatePeriod($start_datetime, $date_interval, $end_datetime);
// iterate until the last date in the set
foreach($date_period as $dp) {
$next_delivery = $dp;
}
?>
<div class="header-next-delivery">
Next delivery: <?php echo $next_delivery->format('l, M j, Y'); ?>
</div>
This seems to work, but I can't help thinking that there must be a more elegant way to do this than having to iterate through a set of dates from the start date to the last date in the set. As time passes, the set will just get bigger and bigger.
Also, I'm having trouble figuring out the internal workings of these functions -- how would I set the exact time that the displayed delivery date bumps forward by two weeks?
Thanks for any insight!
You can get date interval in days from $start_date to current date. Divide it by 14 (two weeks), get remainder and substract it from 14. Then you can add that value of days to current date.
$start_date = date_create('2016-10-27');
$current_date = date_create();
$interval = date_diff($start_date, $current_date);
$days_diff = (int)$interval->format('%a');
$current_date->add(14 - ($days_diff % 14).' days');

PHP adding exact weekdays to a timestamp

I want to add an x number of week days (e.g. 48 weekday hours) to the current timestamp. I am trying to do this using the following
echo (strtotime('2 weekdays');
However, this doesn't seem to take me an exact 48 hours ahead in time. For example, inputting the current server time of Tuesday 18/03/2014 10:47 returns Thursday 20/03/2014 00:00. using the following function:
echo (strtotime('2 weekdays')-mktime())/86400;
It can tell that it's returning only 1.3 weekdays from now.
Why is it doing this? Are there any existing functions which allow an exact amount of weekday hours?
Given you want to preserve the weekdays functionality and not loose the hours, minutes and seconds, you could do this:
$now = new DateTime();
$hms = new DateInterval(
'PT'.$now->format('H').'H'.
$now->format('i').'M'.
$now->format('s').'S'.
);
$date = new DateTime('2 weekdays');
$date->add($hms);//add hours here again
The reason why weekday doesn't add the hours is because, if you add 1 weekday at any point in time on a monday, the next weekday has to be tuesday.
The hour simply does not matter. Say your date is 2014-01-02 12:12:12, and you want the next weekday, that day starts at 2014-01-03 00:00:00, so that's what you get.
My last solution works though, and here's how: I use the $now instance of DateTime, and its format method to construct a DateInterval format string, to be passed to the constructor. An interval format is quite easy: it starts with P, for period, then a digit and a char to indicate what that digit represents: 1Y for 1 Year, and 2D for 2 Days.
However, we're only interested in hours, minutes and seconds. Actual time, which is indicated using a T in the interval format string, hence we start the string with PT (Period Time).
Using the format specifiers H, i and s, we construct an interval format that in the case of 12:12:12 looks like this:
$hms = new DateInterval(
'PT12H12M12S'
);
Then, it's a simple matter of calling the DateTime::add method to add the hours, minutes and seconds to our date + weekdays:
$weekdays = new DateTime('6 weekdays');
$weekdays->add($hms);
echo $weekdays->format('Y-m-d H:i:s'), PHP_EOL;
And you're there.
Alternatively, you could just use the basic same trick to compute the actual day-difference between your initial date, and that date + x weekdays, and then add that diff to your initial date. It's the same basic principle, but instead of having to create a format like PTXHXMXS, a simple PXD will do.
Working example here
I'd urge you to use the DateInterface classes, as it is more flexible, allows for type-hinting to be used and makes dealing with dates just a whole lot easier for all of us. Besides, it's not too different from your current code:
$today = new DateTime;
$tomorrow = new DateTime('tomorrow');
$dayAfter = new DateTime('2 days');
In fact, it's a lot easier if you want to do frequent date manipulations on a single date:
$date = new DateTime();//or DateTime::createFromFormat('Y-m-d H:i:s', $dateString);
$diff = new DateInterval('P2D');//2 days
$date->add($diff);
echo $date->format('Y-m-d H:i:s'), PHP_EOL, 'is the date + 2 days', PHP_EOL;
$date->sub($diff);
echo $date->format('Y-m-d H:i:s'), PHP_EOL, 'was the original date, now restored';
Easy, once you've spent some time browsing through the docs
I think I have found a solution. It's primitive but after some quick testing it seems to work.
The function calculates the time passed since midnight of the current day, and adds it onto the date returned by strtotime. Since this could fall into a weekend day, I've checked and added an extra day or two accordingly.
function weekDays($days) {
$tstamp = (strtotime($days.' weekdays') + (time() - strtotime("today")));
if(date('D',$tstamp) == 'Sat') {
$tstamp = $tstamp + 86400*2;
}
elseif(date('D',$tstamp) == 'Sun') {
$tstamp = $tstamp + 86400;
}
return $tstamp;
}
Function strtotime('2 weekdays') seems to add 2 weekdays to the current date without the time.
If you want to add 48 hours why not adding 2*24*60*60 to mktime()?
echo(date('Y-m-d', mktime()+2*24*60*60));
The currently accepted solution works, but it will fail when you want to add weekdays to a timestamp that is not now. Here's a simpler snippet that will work for any given point in time:
$start = new DateTime('2021-09-29 15:12:10');
$start->add(date_interval_create_from_date_string('+ 3 weekdays'));
echo $start->format('Y-m-d H:i:s'); // 2021-10-04 15:12:10
Note that this will also work for a negative amount of weekdays:
$start = new DateTime('2021-09-29 15:12:10');
$start->add(date_interval_create_from_date_string('- 3 weekdays'));
echo $start->format('Y-m-d H:i:s'); // 2021-09-24 15:12:10

Adjust a PHP date to the current year

I have a PHP date in a database, for example 8th August 2011. I have this date in a strtotime() format so I can display it as I please.
I need to adjust this date to make it 8th August 2013 (current year). What is the best way of doing this? So far, I've been racking my brains but to no avail.
Some of the answers you have so far have missed the point that you want to update any given date to the current year and have concentrated on turning 2011 into 2013, excluding the accepted answer. However, I feel that examples using the DateTime classes are always of use in these cases.
The accepted answer will result in a Notice:-
Notice: A non well formed numeric value encountered......
if your supplied date is the 29th February on a Leapyear, although it should still give the correct result.
Here is a generic function that will take any valid date and return the same date in the current year:-
/**
* #param String $dateString
* #return DateTime
*/
function updateDate($dateString){
$suppliedDate = new \DateTime($dateString);
$currentYear = (int)(new \DateTime())->format('Y');
return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}
For example:-
var_dump(updateDate('8th August 2011'));
See it working here and see the PHP manual for more information on the DateTime classes.
You don't say how you want to use the updated date, but DateTime is flexible enough to allow you to do with it as you wish. I would draw your attention to the DateTime::format() method as being particularly useful.
strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );
This takes the day and month of the original time, adds the current year, and converts it to the new date.
You can also add the amount of seconds you want to add to the original timestamp. For 2 years this would be 63 113 852 seconds.
You could retrieve the timestamp of the same date two years later with strtotime() first parameter and then convert it in the format you want to display.
<?php
$date = "11/08/2011";
$time = strtotime($date);
$time_future = strtotime("+2 years", $time);
$future = date("d/m/Y", $time_future);
echo "NEW DATE : " . $future;
?>
You can for instance output it like this:
date('2013-m-d', strtotime($myTime))
Just like that... or use
$year = date('Y');
$myMonthDay = date('m-d', strtotime($myTime));
echo $year . '-' . $myMonthDay;
Use the date modify function Like this
$date = new DateTime('2011-08-08');
$date->modify('+2 years');
echo $date->format('Y-m-d') . "\n";
//will give "2013-08-08"

PHP Calculating future date by adding days to a variable date

I was looking at this post, and it is close to what I need:
PHP - How to count 60 days from the add date
However, in that post, the calculation is performed by adding 60 days to the current date. What I need to do is calculate the date based on a variable date (and not the current date).
Something like this:
$my_date = $some_row_from_a_database;
$date_plus_10_days = ???;
Anyone know how to do that?
Thanks
You can put something before the "+10 days" part:
strtotime("2010-01-01 +10 days");
Use date_add
http://www.php.net/manual/en/datetime.add.php
$my_date = new DateTime($some_row_from_a_database);
$date_plus_10_days = date_add($my_date, new DateInterval('P10D'));
You will have to look into strtotime(). I'd imagine your final code would look something like this:
$dateVariable = strtotime('2017-01-29');//your date variable goes here
$date_plus_60_days = date('Y-m-d', strtotime('+ 60 days', $dateVariable));
echo $date_plus_60_days;
If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$date_plus_60_days = new DateTime("2006-12-12");
$date_plus_60_days->modify("+60 days");
echo $date_plus_60_days->format("Y-m-d");
I see you are retriving data from a database.
If you are using mysql you can do it on the select:
Example: you need the last date of the table and this date-7 days
select max(datefield) as ultimaf, DATE_SUB(max(datefield),INTERVAL 7 DAY) as last7
from table
It´s easy use curdate() if you want todays date.
If you need a dynamic between that selects the count of last 7 days:
select count(*) from table
where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=datefield"
date('Y-m-d H:i:s', strtotime("2014-11-24 06:33:39" +35 days"))
this will get the calculated date in defined format.
Suppose today's date is
date_default_timezone_set('Asia/Calcutta');
$today=date("Y-m-d");
And i can add 10 days in current date as follows :
$date_afte_10_days = date('Y-m-d', strtotime("$today +10 days"));

Categories