减去与当前日期相比的日期并显示实际剩余天数

时间:2018-12-19 21:29:52

标签: php sql-server

这是我的以下功能:

function Active()
{
    ............

$num_rows = $db->doQuery('SELECT PremiumDays, PremiumStartTime FROM Premium WHERE AccountID = ?', $_SESSION['AccountID']);
if ($num_rows == -1)
{
$this->Error('ERROR');
$db->getError();
return;
}

$data = $db->doRead();
$data['Status'] = $num_rows == 0 ? '<:SHOW_PREMIUM_STATUS:>' : '<b><font size="2" color="red">Premium is active - <%Days_Remaining%> days remaining.</font></b>';

$replace = array
(
'account_status'        => $data['Status'],
'days_remaining'        => number_format($data['PremiumDays'])
);

$this->content = Template::Load('account-template', $replace);
}

PremiumDays列包含101530等数字。

PremiumStartTime包含日期,格式为2018-12-17 21:13:00

我要达到的目的是显示days_remaining剩余的实际保费天数。因此,我认为我需要减去PremiumDays,根据第二列PremiumStartTime,保费开始以来的天数。

但是,我不知道该如何在PHP中正确实现它。任何帮助是极大的赞赏。先感谢您!

days_remaining = PremiumDays - (NumberOfDaysSincePremiumStarted(DateToday - PremiumStartTime))

2 个答案:

答案 0 :(得分:0)

在数据库中执行以下操作:

//SQL Server
$num_rows = $db->doQuery('SELECT PremiumDays, PremiumStartTime, 
             (PremiumDays - datediff(day,PremiumStartTime,getdate())) DaysRemaining 
              FROM Premium WHERE AccountID = ?', $_SESSION['AccountID']);


//MySQL
$num_rows = $db->doQuery('SELECT PremiumDays, PremiumStartTime, 
             (PremiumDays - datediff(now(),PremiumStartTime)) DaysRemaining 
              FROM Premium WHERE AccountID = ?', $_SESSION['AccountID']);

然后:

$replace = array
(
'account_status'        => $data['Status'],
'days_remaining'        => $data['DaysRemaining']
);

此处的证明:https://www.db-fiddle.com/f/xzuc89C9gQUHpdTTy9M4vf/0

或者如果您真的想用PHP做到这一点:

$replace = array
(
'account_status'        => $data['Status'],
'days_remaining'        => $data['PremiumDays'] - date_diff(date_create(), date_create($data['PremiumStartTime']))->days
);

答案 1 :(得分:0)

要获取PHP的不同之处,可以在当前时间(输出DateInterval)和使用DateTime::diff对象创建的date_create()对象之间使用DateTime创建一个days对象。 PremiumStartTime变量。然后,您可以访问该对象的Demo on 3v4l.org值,以获取从PremiumStartTime到当前时间的总天数。例如:

$data['PremiumStartTime'] = '2018-12-12 21:13:00';
$data['PremiumDays'] = 20;
$days_remaining = $data['PremiumDays'] - date_create($data['PremiumStartTime'])->diff(date_create())->days;
echo number_format($days_remaining);

输出:

13

MySql.Data.EntityFrameworkCore