duanbiao4035 2016-01-31 17:39
浏览 64

格式化具有不确定数据的日期

A quick search didn't return any results that seemed to fit what I was looking for so I come here asking for your help.

I am working on formatting a birthday. The problem is, the use has the ability to enter only some (or none) of the data. It is stored separately as day, month, and year.

Basically, based on the data present will determine how the date will be formatted and displayed back to the user.

My approach is:

#prepare birthday
        $bday = new DateTime();
        $bday->setTimezone(new DateTimeZone('America/New_York'));
        $bday->setDate($row->birth_year,$row->birth_month,$row->birth_day);

        if($row->birth_month && $row->birth_year && $row->birth_day){
            //Full birthday entered
            $display_bday = $bday->format('F j, Y');    
        } elseif($row->birth_month && !$row->birth_year && !$row->birth_day){
            //Only a month
            $display_bday = $bday->format('F');     
        } elseif($row->birth_month && $row->birth_year && !$row->birth_day){
            //Only Month and year
            $display_bday = $bday->format('F, Y');  
        }

I was wondering if there is a better way to accomplish this task. I guess I figure there has to be a better way. Thanks in advance. If I need to clarify anything please just ask!

edit: removed unnecessary code

  • 写回答

1条回答 默认 最新

  • duanjia4969 2016-01-31 18:45
    关注

    Your code could output invalid date since you are not filtering input when setting up a DateTime object. When the $row->birth_day equals 0, the DateTime object will move back to previous month (last date).

    So, I suggest to consider that:

    $display_bday = null;
    if ($row->birth_month) {
      if ($row->birth_year) {
        if ($row->birth_day) {
          // day, month, and year
          $display_bday = date('F j, Y', strtotime("$row->birth_year-$row->birth_month-$row->birth_day"));
        } else {
          // month and year
          $display_bday = date('F, Y', strtotime("$row->birth_year-$row->birth_month-01"));
        }
      } else {
        if ($row->birth_day) {
          // day and month
          $display_bday = date('F j', strtotime("2016-$row->birth_month-$row->birth_day"));
        } else {
          // month only
          $display_bday = date('F', strtotime("2016-$row->birth_month-01"));
        }
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等