doumeng1143 2013-10-31 03:30
浏览 71
已采纳

PHP DateTime接受多种格式?

I'm trying to construct a DateTime object with multiple accepted formats.

According to the DateTime::createFromFormat docs, the first parameter (format) must be a string. I was wondering if there was a way to createFromFormats.

In my case, I want the year for my format to be optional:

DateTime::createFromFormat('Y-m-d', $date);
DateTime::createFromFormat('m-d', $date);

so that a user can input just 'm-d' and the year would be assumed 2013. If I wanted multiple accepted formats, would I have to call createFromFormat each time?

Shortest thing for my scenario is:

DateTime::createFromFormat('m-d', $date) ?: DateTime::createFromFormat('Y-m-d', $date);
  • 写回答

1条回答 默认 最新

  • duana1986 2013-10-31 04:11
    关注

    You could create your own class that extends DateTime and add your own method:

    class EasyDateTime extends DateTime {
    
        public static function createFromFormat($string){   
            if (count(explode("-", $string)) === 2) {
                $string = date('Y')."-".$string;
            }
            return parent::createFromFormat('Y-m-d',$string);
        }
    }
    
    var_dump( EasyDateTime::createFromFormat('01-01') );
    // object(DateTime)#1 (3) { ["date"]=> string(19) "2013-01-01 05:11:03" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Europe/Oslo" }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合