doucaishi0077 2014-03-26 13:45
浏览 306
已采纳

如何在php中设置DateInterval?

I've got this function which creates sets an expiration for something. The function takes a couple arguments which have default values. I do this like so:

public static function blockAccount(
    $id,
    $years = 0,
    $months = 0,
    $days = 0,
    $hours = 0,
    $minutes = 0,
    $seconds = 0
) {
    // Determine expiry date for the block
    $date = Text::getDateTime();
    $date->add(
        new \DateInterval(
            'P' . $years . 'Y'
            . $months . 'M'
            . $days . 'D'
            . $hours . 'H'
            . $minutes . 'I'
            . $seconds . 'S'
        )
    );
    $blockedExpiryDate = $date->format(Filter::FORMAT_MICRO_TIMESTAMP);

    $accountModel = AccountModel::selectById($id);
    $accountModel->setBlockedExpiryDate($blockedExpiryDate);
    $accountModel->save();
}

When running this with just the year set, I get an error, saying:DateInterval::__construct(): Unknown or bad format (P1Y0M0D0H0I0S).

Any ideas what I'm doing wrong here?

  • 写回答

1条回答 默认 最新

  • douyao2529 2014-03-26 13:48
    关注

    You're missing the T before your time elements and minutes should be M not I:

    If the duration contains time elements, that portion of the specification is preceded by the letter T.

    $date->add(
        new \DateInterval(
            'P' . $years . 'Y'
            . $months . 'M'
            . $days . 'DT'
            . $hours . 'H'
            . $minutes . 'M'
            . $seconds . 'S'
        )
    );
    

    You may also want to make your code smarter and simply omit any date/time elements that have zero values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0