【问题标题】:Checking for Expiration before 3 months, 1 month and date of expiration in Textbox在文本框中检查 3 个月、1 个月和到期日期之前的到期日期
【发布时间】:2021-02-22 16:50:39
【问题描述】:

我想在我的文本框中查看或提醒 3 个月(黄色)、1 个月(橙色)和到期日期(红色)之前的到期日期。 这是我的代码,但我的条件中只有一个过期日期。

<?php
$today = date('m/d/Y');
$expired = '10/22/2020'; //example
if (strtotime($today) >= strtotime($expired)) {
?>
   Date: <input type="text" name="expired" id="expired" value = "<?php echo $expired; ?>" style="background-color:#F06D6A;"/>      
<?php    
}else {
?>
   Date: <input type="text" name="expired" id="expired" value = "<?php echo $expired; ?>" style="background-color:#FFF;"/>
<?php    
}
?>

【问题讨论】:

  • 小心! strtotime() 会将 12/10/2020 解释为“2020 年 12 月 10 日”,而您预计会是“2020 年 10 月 12 日”!
  • 我将如何解决?

标签: javascript php html datetime


【解决方案1】:

这是处理事情的一种方法。有关分步说明,请参阅 cmets。

<?php

// Careful! strtotime() will interpret 12/10/2020 as "10 December 2020", where you expect it to be 12 October 2020!
// Consider the code below for an alternative, more robust solution.

$today = new DateTime;

// Added time for uniformity.
// "Notice of default" used to indicate the final date for possible payment,
// before services are suspended and/or legal action is taken.
// use setDate() and setTime() to explicitly set the date/time, to avoid caveats with international date formats
// as pointed out above.
$noticeOfDefaultAt = (new DateTime)->setDate(2021, 2, 10)->setTime(7, 0);

// First reminder (yellow) sent 3 months before expiration date.
// DateInterval() accepts a formatted string which decodes here to:
// P = Period of
// 3 = 3
// M = Months
// Use sub() to get the period offset from the final payment date ($noticeOfDefault)
$firstReminderAt = (clone $noticeOfDefaultAt)->sub(new DateInterval('P3M'));
// Second reminder (orange) sent 1 month before expiration date.
$secondReminderAt = (clone $noticeOfDefaultAt)->sub(new DateInterval('P1M'));

// Default to transparent if within payment period.
$bgColor = 'transparent';

if ($today >= $firstReminderAt && $today < $secondReminderAt)
    // Today is within grace period of first reminder.
    $bgColor = 'yellow';

if ($today >= $secondReminderAt && $today < $noticeOfDefaultAt)
    // Today is within grace period of second reminder.
    $bgColor = 'orange';
    
if ($today >= $noticeOfDefaultAt)
    // We have a really sh*tty customer. Send legal team.
    $bgColor = 'red';

// Change the color names to any rgb-hex value you want and use them in your "style" attribute.
echo $bgColor;

【讨论】:

  • 我的日期格式是 m/d/Y,比如 10/22/2020。我如何像这样转换它 setDate(2021, 2, 10)?
  • 如果你没有这些日期组件的整数,你可以像这样得到它们:[$month, $day, $year] = explode('/', $yourDateString);,然后像这样传递它们:setDate($year, $month, $day)。您可以选择在执行此操作之前将它们转换为整数((int)$year+$year)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多