How to say "next month 15th" in PHP's DateTime? - php

What I want to do:
Getting a certain day from a certain month directly via the DateTime methods (no mktime stunts :)), like
$day = new DateTime('15th of next month');
but it's not possible to set a fixed day by it's number.
Can anybody help ?
EDIT: I've changed the DateTime from this month to next month to make the problem more clear.

You can use DateTime::createFromFormat(). If you only pass the day value, it'll default to the current month and year.
$date = DateTime::createFromFormat('d', '15');
echo $date->format('Y-m-d'); // 2018-10-15
Edit for the new question requirements:
$date = DateTime::createFromFormat('d', 15)->add(new DateInterval('P1M'));
echo $date->format('Y-m-d'); // 2018-11-15

Related

PHP dateTime previous month of 31 Dec is wrong

I have this:
$previousMonth = new DateTime('2019-12-31');
$previousMonth->modify('-1 month');
My understanding is '-1 month' should modify the object regardless of number of days in that month, or?
Naturally what should I get or expect to get is end of Nov(2019-11-30) but what I get is first of December(the same month).
BTW if I change the date to '2019-12-30'(one day prior) then it will be end of Nov.
If my initial assumption is not correct, then what is the best alternative to reliably calculate the previous month?
Any thoughts?
The simplest and easiest way to get the last month in php is
$previousMonth = date("Y-n-j", strtotime("last day of previous month"));
Same as been suggested on other thread Getting last month's date in php
$date = "2019-12-31 00:00:00";
echo date('Y-m-d', strtotime($date . '-1month'));
This prints out 2019-12-01 as the 31/11 does not exist.
The following doesn't answer your question but may help in the future. I like to use Carbon when working with dates. Your issue could be resolved quite simply with this.
https://carbon.nesbot.com/
It has many functions and is extremely simple to use, and it can be installed with Composer.
To get the last day of the previous month, you can get the first day of the current month and substract 1 second or 1 day :
$previousMonth = new DateTime('2019-12-31');
$previousMonth->modify($previousMonth->format('Y-m-01')); // date is 2019-12-01 00:00:00
$previousMonth->modify('-1 sec');
echo $previousMonth->format('Y-m-d H:i:s') . PHP_EOL; // Outputs 2019-11-30 23:59:59
$previousMonth->modify('+1 sec'); // set back the original date 2019-12-01 00:00:00
$previousMonth->modify('-1 day');
echo $previousMonth->format('Y-m-d H:i:s'); // Outputs 2019-11-30 00:00:00

PHP get current datetime + one year (also asking if secure)

just trying to create a variable where it outputs the exact current datetime and adding exactly one additional year. how do i add the days?
$expirationdate = date('Y-m-d H:i:s', .' + 1 year'));
Lets say the exact current date is 2019-01-23 17:11:25
the variable will be: 2020-01-23 17-11-25 (+365)
Also, if a person manually modifies the date on their PC/Phone, will that time be the start of the current date on the variable?
You can achieve your result by using strtotime() and date() function of php
$expirationdate = date('Y-m-d H:i:s', strtotime('+ 1 year'));
print_r($expirationdate);
You can read more about the strtotime() and date()
Try with below code:
$expirationdate = date('Y-m-d H:i:s', strtotime('+1 years'));
I hope it will help you.
Try This :
$date= date('Y-m-d H:i:s',strtotime('+1 years'));
I think the best way to work with dates and time in PHP is through the DateTime object. You can use modify method to add or subtract days, years or whatever you want, like this:
$d = new DateTime(); //current date
$d->modify('+10 days');
$d->modify('+1 year');
echo $d->format('Y-m-d H:i:s');
Regarding your second question if a person modifies date on his computer it won't change anything because PHP runs on the server and takes date from it (not from the user machine).

If date has passed in this year, get it from next year

I'm using Carbon for the dates. Let's take 1st of March for example. By default Carbon returns the 1st of March for the current year.
//Returns current year value
$date = Carbon::parse('first day of March');
Is it possible to get it definitely from the future (next year), if it has already passed in this year, without using if conditions.
//Shorten this part
$date = Carbon::parse('first day of March');
if ($date->lessThanOrEqualTo(Carbon::now())) {
$date->addYear();
}
$output = $date->format('d-m-Y');
Carbon is just a wrapper class for PHP's DateTime class.
Therefore, this should work:
<?php
$date = new DateTime('2018-03-01');
$today = new DateTime();
if ($date < $today) {
$date->modify('+1 year');
}
echo $date->format('d/m/Y');
Output: 01/03/2019
See it working here https://3v4l.org/i1HvL
Learn the actual PHP DateTime class here https://secure.php.net/manual/en/class.datetime.php
I have no idea why you wouldn't use if to check IF something. Maybe you'd like a ternary better?
$date = ($date < $today) ? $date->modify('+1 year') : $date;
Maybe not cleaner than your method, but it's different and it's working.
I create an array with all the dates relevant, today, 1 of March, and 1 of March next year and sort them.
Then I find 'today' with array_search in the array and grab the next value.
$date = array(Carbon::parse('today'),Carbon::parse('first day of March'), Carbon::parse('first day of March + 1 year'));
sort($date);
$date = $date[array_search(Carbon::parse('today'), $date)+1];
var_dump($date);
I honestly think this is slower than a if(), but it does not use an if() as OP requested :-)

'Round' up a date to the beginning of the next month

I need to take an existing date from a variable and display a date that is always the 1st day (01) of whatever the next month is (and accounting for the year as well).
So if I have this:
$date = '2017-03-17'; // YYYY-MM-DD
I need to take that date and make it output this:
2017-04-01 // The first day of the next month
Just another example...
$date = '2017-12-23'; // YYYY-MM-DD
...should be converted to...
2018-01-01 // The first day of the next month
You can use DateTime like:
$dateTime = new DateTime('2017-03-17');
$dateTime->modify('first day of next month');
echo $dateTime->format('Y-m-d');
Simply increment the date by 1 month and set the date to 1st of the month. Do -
date('Y-m-01', strtotime('+1 MONTH', strtotime($date)));
Working code
you can get it using
$date = '2017-03-17';
echo date('Y-m-01', strtotime('+1 month',strtotime($date)));
https://eval.in/790237

How do I remove 3 months from a date?

Assume the date is:
$date = "2011-08-28";
It need to calculate 3 months previous to $date - how can that be done?
$new_timestamp = strtotime('-3 months', strtotime($date));
You can then use the new timestamp with the php date() function to display the new date how you wish, for example:
echo date("Y-m-d",$new_timestamp);
For me this way is much better because the code is more readable.
$datetime = Datetime::createFromFormat('Y-m-d', "2011-08-28");
$datetime->modify('-3 months');
echo $datetime->format('Y-m-d');
edit: I'm an idiot. You could do the above as follows
$datetime = new Datetime("2011-08-28");
$datetime->modify('-3 months');
echo $datetime->format('Y-m-d');
edit: As pointed out by calumbrodie, you can use the sub method instead of inverting the interval and adding it to the date object
I was trying to do something similar to the original question. I needed to subtract 1 day from a DateTime object. I know the other solutions work, but here's another way I liked better. I used this function:
function getPreviousDay($dateObject){
$interval = new DateInterval('P1D');
$dateObject->sub($interval);
return $dateObject;
}
$dateObject is a DateTime object that can have any date you wan't, but as I wanted the current date, I wrote:
$dateObject = new DateTime('now');
What my function does, is subtract 1 day from the date it receives, but you can modify it so it subtracts 3 months modifying the DateInterval constructor like this:
$interval = new DateInterval('P3M');
$dateObject->sub($interval);
return $dateObject;
You can find the explanation on the string format used in the DateInterval constructor here
DateInterval constructor documentation
There you'll se that letter 'P' (period) is mandatory, the you use an int to specify period length and then specify the period type, in the case of months 'M'. It looks as if there was an error in the documentation, it says that "M" is used for months and minutes, but it actually works for months. If you need to use minutes, you must specify "PTM", for example "PT3M" for 3 minutes, outside the table it says you must use the "T" identifier for time intervals.
edit:
To give a complete example, you have to use this format for a full date time interval:
$format = 'P1Y2M4DT2H1M40S';
This will represent an interval of 1 year, 2 months, 4 days, 2 hours,1 minute and 40 seconds
Hope this helps someone
<?php
$threemonthsago = mktime(0, 0, 0, date("m")-3, date("d"), date("Y"));
?>
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

Categories