dongtanhe4607 2012-06-27 13:36
浏览 74
已采纳

从输入字符串格式化日期时间

I'm doing a date search filter where I have my date displayed as "j.n.Y G:i (26.6.2012 15:22)". A user can enter the whole date or only a portion of it: "26.6","6.2012","6","15:22" are all valid inputs. Because I need to check this date in the database the format needs to be changed to the one of the database. For that I use:

$datum = '25.6.2012';
$date = DateTime::createFromFormat('j.n.Y',$datum);
echo $date->format('Y-m-d H:i');

Where I get an error if $datum is not in the format j.n.Y (if I only enter j.n or one of the above mentioned string portions i get an error).

A problem is also, for the entered string 'j.n.Y', i get the right output of the date, which also has the current time added to the date string (which was not in the initial date string). Example: I enter "22.6.2012", then I get the output "2012-06-22 15:33".

Can these two problems get fixed with existing php functions or should I make my own?

Help would be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • dongnaopa6200 2012-06-27 13:45
    关注

    You can list your acceptable data formats in an array, and loop around DateTime::createFromFormat() to see if any of the inputs produce an acceptable date:

    $formats = array( 'j.n', 'j.n.Y');
    $datum = '25.6.2012'; $date = false;
    
    foreach( $formats as $format) {
        $date = DateTime::createFromFormat( $format, $datum);
        if( !($date === false)) break;
    }
    
    if( $date === false) {
        echo "Invalid date!
    ";
    }
    

    Finally, if you want to get rid of the current time in the newly created object and set the time to 00:00:00, just use the setTime() method on the date object:

    // Sets the time to O hours, 0 minutes, 0 seconds
    $date->setTime( 0, 0, 0);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题