DateTime Class 使用

DateTime vs DateTimeImmutable

DateTime 使用modify/add/sub 等修改后,本身时间对象也会跟着修改,format输出的就是最新的时间

DateTimeImmutable修改后,本身时间对象不会修改,相关修改方法返回一个新的时间对象,用新的对象进行赋值才会修改原来的对象

修改时间方法

motify(使用方法和date类似, 传入的参数string和date构造string规则相同)

参考: https://www.php.net/manual/en/datetime.formats.relative.php

代码例子:

这里用放款后生成的一个还款通知举例

$returnTime = new DateTimeImmutable($loan['return_time']); //放款时间
$nextMonth = $returnTime->modify('first day of next month'); //下月开始还款
$notifyTime = $nextMonth->modify('+'. $loan['repayment_notify_day'] . ' days'); //还款通知时间
$repaymentTime = $nextMonth->modify('+'. $loan['repayment_last_day'] . ' days'); //最后还款时间
$notifies = [];

//$schedules 是计算出的每月应还利息本金信息
foreach ($schedules as $schedule) {
    $notifies[] = [
        'customer_id' => $loan['customer_id'],
        'loan_id' => $loan['id'],
        'notify_data' => $notifyTime->format('Y-m-d'),
        'repayment_date' => $repaymentTime->format('Y-m-d'),
        'month' => $notifyTime->format('Ym'),
        'capital_amount' => $schedule['capital'],
        'interests_amount' => $schedule['interests'],
        'total_amount' => round($schedule['interests'] + $schedule['capital'], 2),
        'status' => 'wait',
        'index' => $schedule['index'],
        'notify_time' => null,
    ];
    $notifyTime = $notifyTime->modify('+1 month');
    $repaymentTime = $repaymentTime->modify('+1 month');
}

//$notifies 就是生成的每月还款通知的对应信息了 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注