duanchazhou6779 2013-09-08 22: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-08 22: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部