duanchazhou6779 2013-09-09 06:38
浏览 55
已采纳

在PHP中将前导零添加到字符串日期

I have a string "date" which can be DD.MM.YYYY or D.M.YYYY (with or without leading zeros), it depends what a user types. Then I use it in a condition to send another email when the day is today.

if($_POST["date"]== date("d.m.Y")){ 
  $headers.="Bcc: another@mail.cz
";
}

The problem is that the mail is send when the date format DD.MM.YYYY (with leading zeros) only.

My proposed solution

As I'm not very good in PHP, I only know the solution theoretically but not how to write the code - I would spend a week trying to figure it out on my own.

What's in my mind is dividing the date into three parts (day, month, year), then checking the first two parts if there's just one digit and adding leading zeros if it's the case. I don't know how to implement that to the condition above, though. I have read a few topics about how to do this, but they were a bit more different than my case is.

  • 写回答

3条回答 默认 最新

  • douyu5679 2013-09-09 06:41
    关注

    You should equalize to same format d.m.Y and you can do this with strtotime and date function:

    $post_date = date("d.m.Y", strtotime($_POST["date"]));
    
    if($post_date == date("d.m.Y")){ 
      $headers.="Bcc: another@mail.cz
    ";
    }
    

    I changed date to $post_date for more clear. I'll try to explain difference with outputs

    echo $_POST["date"]; // lets say: 8.7.2013
    
    echo date("d.m.Y"); // 09.09.2013 > it's current day
    
    strtotime($_POST["date"]); // 1373230800 > it's given date with unix time
    
    $post_date = date("d.m.Y", strtotime($_POST["date"])); // 08.07.2013 > it's given date as right format
    

    If you use date function without param, it returns as current date.

    Otherwise if you use with param like date('d.m.Y', strtotime('given_date'));, it returns as given date.

    $post_date = date("d.m.Y", strtotime($_POST["date"]));
    

    At first, we converted your date string to unix with strtotime then equalized and converted format that you used in if clause.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?