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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?