33 Votes

PHP: Date 3 Months ago

Question by Compi | Last update on 2021-04-06 | Created on 2014-08-11

In one of my PHP scripts, I need the date that is exactly 3 months ago. For example, if the current day is 11.8, I would like to get 11.5.

Up to now, I have used the following code for my purpose:

echo date("d.m.Y", time()-7776000); 

The number 7776000 is composed of 60 seconds * 60 minutes * 24 hours * 30 days * 3 months. In other words, this number should represent the number of seconds, passing by in one months and my idea was to subtract this value from the current time determined with time().

The problem: Not every month has 30 days. Therefore, I do not get the "exact" day three months ago with this ansatz. Instead, I get one day located somewhere my desire today around depending on the number of days of the last months.

Another idea was to take the month as an integer number in order to subtract 3 from this value, but this is leading to problems whenever the day falls into another year (for example when trying to subtract three months from January or February).

It's tricky. Can someone help me?

ReplyPositiveNegative
1Best Answer7 Votes

Just use the following line of code instead and let PHP take over the computing work for you:

echo date("d.m.Y", strtotime("-3 Months"));

This should always return your desire date with the same day of the month, that is exactly "three months" in the past.
Last update on 2021-04-06 | Created on 2014-08-11

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Determine Week Number

Tutorial | 0 Comments

Change Date of File

Tutorial | 0 Comments

VirtualBox: Change Date and Time

Tutorial | 10 Comments

PHP: Add X Months to a Date

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.