pau*_*aul 3 php validation datetime date credit-card
我正在尝试使用DateTime检查信用卡到期日期是否已过期,但我有点迷失.
我只想比较mm/yy日期.
到目前为止,这是我的代码
$expmonth = $_POST['expMonth']; //e.g 08
$expyear = $_POST['expYear']; //e.g 15
$rawExpiry = $expmonth . $expyear;
$expiryDateTime = \DateTime::createFromFormat('my', $rawExpiry);
$expiryDate = $expiryDateTime->format('m y');
$currentDateTime = new \DateTime();
$currentDate = $currentDateTime->format('m y');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
Run Code Online (Sandbox Code Playgroud)
我觉得我差不多了,但if语句产生的结果不正确.任何帮助,将不胜感激.
Joh*_*nde 11
它比你想象的要简单.您正在使用的日期格式并不重要,因为PHP在内部进行比较.
$expires = \DateTime::createFromFormat('my', $_POST['expMonth'].$_POST['expYear']);
$now = new \DateTime();
if ($expires < $now) {
// expired
}
Run Code Online (Sandbox Code Playgroud)
您可以使用DateTime类使用DateTime :: createFromFormat()构造函数生成与给定日期字符串格式匹配的DateTime对象。
格式('my')将匹配字符串格式为'mmyy'的任何日期字符串,例如'0620'。或者,对于具有4位数字年份的日期,请使用格式“ mY”,它将与具有以下字符串模式“ mmyyyy”的日期匹配,例如“ 062020”。使用DateTimeZone类指定时区也是明智的。
$expiryMonth = 06;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone);
Run Code Online (Sandbox Code Playgroud)
有关更多格式,请参见DateTime :: createFromFormat页面。
但是-对于信用卡/借记卡的到期日期,您还需要考虑完整的到期日期和时间 -而不仅仅是月份和年份。
如果未指定,DateTime :: createFromFormat将默认使用当月的今天(例如17)。这意味着信用卡还需要几天才能显示过期。如果卡在06/20(即2020年6月)到期,则实际上在2020年7月1日的00:00:00停止工作。修改方法可解决此问题。例如
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone)->modify('+1 month first day of midnight');
Run Code Online (Sandbox Code Playgroud)
该字符串'+1 month first day of midnight'执行三件事。
Modify方法对于许多日期操作确实非常有用!
因此,要回答操作,这是您需要的:
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat(
'my',
$_POST['expMonth'].$_POST['expYear'],
$timezone
)->modify('+1 month first day of midnight');
$currentTime = new \DateTime('now', $timezone);
if ($expiryTime < $currentTime) {
// Card has expired.
}
Run Code Online (Sandbox Code Playgroud)
小智 5
以上答案的补充。请注意,默认情况下,天也将在计算中。例如今天是2019-10-31,如果运行此命令:
\DateTime::createFromFormat('Ym', '202111');
Run Code Online (Sandbox Code Playgroud)
它将输出2021-12-01,因为在11月不存在第31天,它将为DateTime对象增加1天,其副作用是您将在12月而不是预期的11月。
我的建议是始终在代码中使用这一天。