首页 文章

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

提问于
浏览
-1

我正在访问一个访问网站,付费会员将完全 3 months access period 到该网站 . 因此,问题是如何计算确切的3个月日期 .

即,有些月份是28天,其他月份是31天;正常年份是365,但农历年是354天 .

我正在考虑将日期转换为 UNIX timestamps 然后以秒为单位计算3个月 . 但我不确定这是否是最有效和最准确的方法 .

以下是我的提议,我真的很感激一些建议;

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

就像我说的,这是我想出的最好的,但我怀疑它不准确 .

真的适合一些建议

3 回答

  • 0

    正如我在评论中所说,只需将DateTime对象的 add() 方法与DateInterval一起使用即可

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

    php 5的 DateTime class 非常稳定,并在相应使用时带来准确的结果 . 使用DateTime类时,建议您始终为时差精度目的设置TimeZone .

    //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.
    
  • 1

    将我的评论转换为答案......

    你可以使用php内置函数strtotime来实现这一点 . 这个功能 Parse about any English textual datetime description into a Unix timestamp .

    因此,如果您已经在使用unix时间戳,那么从现在起3个月就可以执行此操作,以unix时间戳表示:

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

    如果要输出值,它看起来像这样:

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

    请注意,如果您手动进行计算,则会有很大不同;即

    <?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
    
    ?>
    

相关问题