使用日期对象计算日期时间的最准确方法

i am working on an access site, paying members will get exactly 3 months access period to the site. the issue therefore is how to calculate an exact 3 month date period.

i.e, some months are 28 days, others are 31 days; normal years is 365 but lunar year is 354 days.

i was thinking of converting the date to a UNIX timestamps and then calculating 3 months in seconds. But i am not sure whether this is the most efficient and accurate way to do it.

below is my proposal , i would really appreciate some advice on it;

timestamp when the clocks starts

$UNIXtimeStampNow   =   new \DateTime("now"))->format('U')

calculating 3 months from date:

  $numberDaysInMonth  = 30.41 = 365/ 12   //number of days in months

  $numberSecondsInDay  = 86400; //number seconds in a day

 $secondsIn3Months  = ($numberDaysInMonth * $numberSecondsInDay) * 3  //number seconds in 3 months

    new \DateTime("$secondsIn3Months"); //convert back to date object

like i said, this is the best i came up with, but i suspect that its not accurate.

would really appropriate some advice

As I said in my comment, just use the DateTime object's add() method with a DateInterval

$d = new \DateTime("now");
$d->add(new \DateInterval('P3M'));
echo $d->format('Y-m-d H:i:s');

Converting my comment into answer...

You can use the php built-in function strtotime to achieve this. This function Parse about any English textual datetime description into a Unix timestamp.

So, if you are already working with unix timestamps, you can do this to get 3 months from now, represented in unix timestamp:

$three_months_from_now = strtotime("+3 month");

If you were to output the value, it would look something like this:

echo date('d/m/Y H:i:s a', strtotime("+3 month"));
// outputs: 10/01/2015 11:32:42 am

Note, this is significantly different, if you doing the calculations yourself manually; i.e.

<?php

$now = time();
$one_hour = 3600; // seconds
$one_day = $one_hour * 24;
$one_month = 30 * $one_day;
$three_months = 3 * $one_month;

echo date('d/m/Y H:i:s a', $now + $three_months);

// outputs: 08/01/2015 10:34:24 am

?>

The DateTime class of php 5 is pretty stable and brings accurate results when used accordingly . When using the DateTime class it is recommended that you always set the TimeZone for Time difference accuracy purposes.

//the string parameter, "now" gets us time stamp of current time 
/*We are setting our TimeZone by using  DateTime class
Constructor*/
$first = new DateTime("now",new DateTimeZone('America/New_York'));

// 3 months from now and again setting the TimeZone
$second = new DateTime("+ 3 months",new DateTimeZone('America/New_York'));

$diff = $second->diff($first);

echo "The two dates have $diff->m months and $diff->days days between them."; 

output: The two dates have 3 months and 92 days between them.