[英]check the format of a date in PHP
我有一個日期輸入,要求用戶按以下格式輸入日期:DD-MM-YYYY - 然后轉換為 YYYY-MM-DD
我想檢查一下他們是否輸入了正確的格式。 即,如果輸入了除 DD-MM-YYYY 之外的任何其他內容,那么它應該會產生錯誤消息
我目前使用以下
list($y, $m, $d) = explode('-', $date);
if(checkdate($m, $d, $y)){
}else{
die("The date was in the wrong format");
}
我嘗試將后面的代碼放在 if 語句中,以及根本不包括 else - 但它不起作用。 關於我可以嘗試什么的任何建議? 謝謝
您要求用戶輸入DD-MM-YYYY ,但您的list()
調用需要explode()
順序為YYYY-MM-DD 。
將您的代碼更新為:
list($d, $m, $y) = explode('-', $date);
只需反轉聲明:
list($d, $m, $y) = explode('-', $date);
if(!checkdate($m, $d, $y)){
die("The date was in the wrong format");
}
// your code here
試試這些
http://roshanbh.com.np/2008/05/date-format-validation-php.html
http://www.plus2net.com/php_tutorial/date-validation.php
最好先在客戶端使用 js 進行驗證,然后你可以做 php 驗證。
為什么頁面應該提交
$in = '31-05-2011';
$ts = date_create_from_format('d-m-Y', $in);
$out = date_format($ts, 'd-m-Y');
if ($in === $out) {
... it's correctly formatted
}
請注意,這不會捕獲諸如 2011 年 3 月 4 日的“03-04-11”之類的錯誤,而用戶實際上是指 2003 年 4 月 11 日。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.