当前位置:网站首页>如何在 PHP 中进行日期格式验证检查(正则)
如何在 PHP 中进行日期格式验证检查(正则)
2022-06-23 06:13:00 【stwood007】
日期检查是任何系统的必备功能。我想介绍一下如何立即用 PHP 检查日期。
日期格式检查
用PHP查看日期的方法主要分为两步。
首先,检查日期格式。日期格式检查是“YYYY-MM-DD”或“YYYY/MM/DD”等格式检查。
有很多方法可以做到这一点,但我认为最好使用正则表达式进行检查。
if(!preg_match('/^[1-9]{1}[0-9]{0,3}\/[0-9]{1,2}\/[0-9]{1,2}$/', $date))
{
return false;
}
上面的示例允许“YYYY/MM/DD”格式的“1/0/0”到“9999/99/99”的值。
你很快就会注意到这里的 0/0 和 99/99 并不存在。为了保存它,需要下一步,即日期的存在性检查。
日期存在检查
日期的存在检查是使用 PHP 函数完成的:“checkdate”。
list($y, $m, $d) = explode('/', $date);
if(!checkdate($m, $d, $y))
{
return false;
}
请注意,“checkdate”函数具有西方日期表示法格式,因此它的格式为“月、日、年”,而不是日本的“年、月、日”。
使用 PHP 进行日期检查 (YYYY / mm / dd)
在实际项目中,年份固定为4位数、月份、日期的情况很多,比如“2013/01/02”,这里就一并提供。具体还是要根据需求来修改。
function isYmd($date){
//如果没有输入,则通过
if ($date == '') {
return true;
}
//19xx和20xx有效,这里只控制月份和日期的位数,//通过下面的checkdate函数进行存在性检查。
if(!preg_match('/^(19|20)[0-9]{2}\/\d{2}\/\d{2}$/', $date)){
return false;
}
list($y, $m, $d) = explode('/', $date);
if(!checkdate($m, $d, $y)){
return false;
}
return true;
}
边栏推荐
- 嵌入式实时系统线程的副作用
- MySQL function
- Why does TCP protocol shake hands three times instead of two?
- 关于五险一金你需要知道的事情
- 聚焦行业,赋能客户 | 博云容器云产品族五大行业解决方案发布
- [QT] basic learning notes
- Easy EDA learning notes 09 esp32-wroom-32e module esp32-devkitc-v4 development board one click download circuit
- Storage mode of data in memory (C language)
- 为什么TCP协议是三次握手而不是两次?
- Problem: when the attribute in the data object (defined data) in the access component is also the attribute in the object object, an error is reported
猜你喜欢

Chrome删除重复书签

MySQL重做日志 redo log

js 判断两个数组增加和减少的元素

Xiaobai must see in investment and wealth management: illustrated fund buying and selling rules

【STL】pair用法总结

20220621 Dual Quaternion

如何迁移virtualbox 的虚拟机到hype-v

RFID数据安全性实验:C#可视化实现奇偶校验、CRC冗余校验、海明码校验

Summary of qvariant use in QT

Sword finger offer 42 Maximum sum of successive subarrays
随机推荐
Miscellaneous things
Swagger3 integrates oauth2 authentication token
关于职业态度
centos7 mysql 记录
js 判断两个数组增加和减少的元素
关于监督
Business logic design of physical warehouse and virtual warehouse in middle inventory
Usage Summary of item views and item widgets controls in QT
Drawing and resetting of mars3d point, line and surface
Xxl-sso enables SSO single sign on
The illustration shows three handshakes and four waves. Xiaobai can understand them
C language operator priority formula
Concepts and differences of DQL, DML, DDL and DCL
【STL】pair用法总结
core. What is JS ---kalrry
MySQL redo log redo log
【BULL中文文档】用于在 NodeJS 中处理分布式作业和消息的队列包
[project training] multi segment line expanded to parallel line
js数组的索引为何不能用负数
About Supervision