简体   繁体   中英

find date months ago, will it miss dates if current month is shorter?

I am writing a script to query dates "3 months ago". As I am thinking about making sure I do not miss anything, I am using this for comparison:

$date = date("Y-m-d",mktime(0,0,0,date("m")-$months_ago,date("d")));

I am realizing there is a chance I could be missing dates. For example, if I search on 11/30 for dates three months ago, I will get 8/30. But the next day is 12/1 and three months prior is 9/1. So in this script I have missed 8/31.

I guess the best method is to use days (90 days) instead on months. Is this the best practice for something like this?

Go directly with strtotime('-3 month'); you can also give negatives like -3 on the month param of the mktime and it will work like charm (better the second solution). No, it wont skip days - if "now" is 2011-06-17 it would return timestamp equivalent to 2011-03-17.

Edit: Well, it might actually be true that you can miss days (I haven't checked your statement) but after all your unit of measurement of time is months, not days. What I'm saying is that in the Gregorian calendar month isn't constant amount of time - it could be 28, 29, 30 or 31 days.

Let's say you want to calculate months for a paid subscription period. If the user pays one month on 2011-02-15, when would his subscription expire? I would guess 2011-03-15, even though there are just 28 days between those two dates And if he pays for subscription on 2011-03-15, he would get full 31 days till 2011-04-15 and this seems perfectly fair to me as the subscription is "one month", which just happens to be different amount of days through the year.

If, in your case you don't want to get "3 months ago" but want to get constant amount of time that relatively represents "3 months", then you can use the medium month length - 88.59 days, or 88 days 14 hours and 10 minutes. That represented with code would be:

strtotime('-88 days -14 hours -10 minutes');

$when = strtotime('-3 months');

If you just need the month/year and don't want to have to calculate days:

$m = 5;  // how many months ago, for example

$now = time();
$cm = date("m",$now); // current month
$yr = date("Y",$now) - intval((12 + $m - $cm)/12);
$month = (($cm + 11 - ($m % 12) ) % 12) + 1;

echo "$m months ago: $month  yr: $yr\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM