简体   繁体   English

Php验证24小时时间格式

[英]Php validating 24 hour time format

I'm allowing users to pick an hour from 00:00:00 to 23:00:00 and need to check if they submit the right format.我允许用户选择从00:00:0023:00:00的一个小时,并且需要检查他们是否提交了正确的格式。 Is there a regular expression or php function that validates a 24 hour format eg HH:MM:SS ?是否有验证 24 小时格式的正则表达式或 php 函数,例如HH:MM:SS

I found some regex examples but the 24 hour time I'm validating is always set to 00 for minutes and seconds.我找到了一些正则表达式示例,但我正在验证的 24 小时时间始终设置为00分钟和秒。 Only the hour varies.只有时间不同。

For example例如

18:00:00, 23:00:00, 01:00:00

This matches 24 hour time including seconds这匹配 24 小时时间,包括秒

([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

If you only want 00 for minutes and seconds, then如果你只想要 00 分钟和秒,那么

([01]?[0-9]|2[0-3]):00:00

Here its a final sample there are ready to be used.这是一个可以使用的最终样本。

$myTime = '23:00:00';

$time = preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $myTime);

if ( $time == 1 )
{
  // make a error!
}
else
{
  // make a error!
}

Try This试试这个

$time="23:00:00";

preg_match('#^([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', $time);

Check it by this function and you can add this function in CodeIgniter helper file of Laravel global helper functions file and call it more times通过这个函数检查,你可以在Laravel global helper functions file的 CodeIgniter 辅助文件中添加这个函数,并多次调用它

<?php
if(!function_exists("check_24_timeFormat")) {
    /**
     *
     * This for check time is in  24 time format  
     * 
     * @param string $time  [ $time => time in 24 hours format like 23:00:00 ]
     * @author Arafat Thabet <arafat.733011506@gmail.com> 
     * @return bool
     */
    function check_24_timeFormat($time){
        if (preg_match("#((0([0-9])|(1[0-9]{1})|(2[0-4])):([0-5])([0-9]):([0-5])([0-9]))#", $time)) {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Has it to be a RegEx?它必须是正则表达式吗? You can easily use PHPs strtotime -function to validate dates and times (does also work without a date).您可以轻松地使用 PHP 的strtotime函数来验证日期和时间(也可以在没有日期的情况下工作)。 strtotime returns false ( -1 prior to PHP 5.1) if the given time isn't valid.如果给定时间无效,则strtotime返回false (PHP 5.1 之前为-1 )。 Don't forget to use the === operand therefore!因此不要忘记使用===操作数!

if (strtotime("12:13") === false) { echo("Wrong Time!"); } // Echos nothing
if (strtotime("19:45") === false) { echo("Wrong Time!"); } // Echos nothing
if (strtotime("17:62") === false) { echo("Wrong Time!"); } // Echos 'Wrong Time!'

This worked like a charm for me.这对我来说就像一个魅力。

$time = "23:59:60";    
preg_match("/^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $time)

Although the selected answer is absolutely fine, I'm not a stickler for imposing formats.虽然选择的答案绝对没问题,但我不是强加格式的坚持者。 I'm of the frame of mind that if you can interpret the data, then the format doesn't really matter.我的想法是,如果您可以解释数据,那么格式并不重要。 Of course the loser you are with formats, the more assumptions you make, and the more risk you take.当然,格式越多,您做出的假设越多,您承担的风险就越大。 But providing a confirmation screen usually fixes assumptions.但提供确认屏幕通常会修正假设。 So, I wrote:所以,我写道:

/* Sample usage:
 *  echo '<ol>',
 *       '<li>validateTime ("13:23") = ',       (validateTime ('13:23')     ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 ") = ',      (validateTime ('03:23 ')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 Am") = ',    (validateTime ('03:23 aM')  ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23Am") = ',     (validateTime ('03:23aM')   ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("03:23 pM") = ',    (validateTime ('03:23 pM')  ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("323") = ',         (validateTime ('323')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("058") = ',         (validateTime ('058')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("1323pm") = ',      (validateTime ('1323pm')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("1323am") = ',      (validateTime ('1323am')    ? 'TRUE' : 'FALSE'), '</li>',   // TRUE - I think this one makes sense, but I'm not sure. 13th hour of the day, starting in the AM?
 *       '<li>validateTime ("323pm") = ',       (validateTime ('323pm')     ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("3") = ',           (validateTime ('3')         ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("3PM") = ',         (validateTime ('3PM')       ? 'TRUE' : 'FALSE'), '</li>',   // TRUE
 *       '<li>validateTime ("13:73") = ',       (validateTime ('13:73')     ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '<li>validateTime ("25:23") = ',       (validateTime ('25:23')     ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '<li>validateTime ("Any crap") = ',    (validateTime ('Any crap')  ? 'TRUE' : 'FALSE'), '</li>',   // FALSE
 *       '</ol>';
 */
function validateTime ($testTime)
{
    define ('regExpPattern', '/^([01]?[0-9]|2[0-3])([:]?[0-5][0-9])?[ ]?([apAP][mM])?$/');

/*      regExpPattern explanation
            /^          # String must begin with.
            (           # Start group.
            [01]        # A 0 or 1.
            ?           # Optionally.
            [0-9]       # 0 through 9.
            |           # Or.
            2           # 2.
            [0-3]       # 0 through 3.
            )           # End of group. This group will match hour in a 24 hour clock.
            (           # New group.
            [:]?        # Optional colon.
            [0-5][0-9]  # Minutes, 00 through 59.
            )           # End of group.
            ?           # Make previous group optional.
            [ ]?        # Optional space.
            (           # New group.
            [apAP]      # One of the following 'apAP'.
            [mM]        # One of the following 'mM'.
            )           # End of group.
            ?           # Make previous group optional. This allows for things like 3 o'clock.
            $/          # Must end with. */

    return preg_match (regExpPattern, trim ($testTime));
}   // function validateTime ($testDate)

Please let me know if you see improvements or bugs.如果您看到改进或错误,请告诉我。

Should I accept other separators.我应该接受其他分隔符吗? What if someone chooses to enter 13.45?如果有人选择输入 13.45 怎么办? Should that be a valid time?那应该是有效时间吗? After all, I do know what the user means.毕竟,我确实知道用户的意思。

Now the next step would be to take the user's input for all possible formats and make it SQL friendly.现在下一步是获取所有可能格式的用户输入,并使它对 SQL 友好。

Enjoy,享受,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM