doutong7216 2016-02-12 17:51
浏览 16

在我的PHP代码中,我使用函数转换日期? [重复]

This question already has an answer here:

(I've had to edit this post since John Conde wrongly marked it as answered because he didn't understand my question.)

In my PHP app, the user should be able to enter a date in any format the strtotime() function understands. Here is the input:

    <label>Release Date:</label>
    <input type="text" name="release_date"/>&nbsp;<span>Use any valid 
           date format</span>
    <br />

Then the index page draws it from the form and stores it in the database like this...

$release_date = $_POST['release_date'];

and displays it on the list page like this:

<td><?php $date = date('n/j/Y', strtotime($product['releaseDate'])); 
                      echo $date; ?></td>

I know how to convert dates from one format to another. The display side is fine. But WHERE and HOW do I take the user input - entered in ANY date format the strtotime() function can interpret - and turn it into a readable format going into the database? Right now if I enter any date not in 'xxxx-xx-xx' format it's read as 0 and comes out as UNIX 0, 1/1/1970.

Thank you.

</div>
  • 写回答

1条回答 默认 最新

  • doupo1908 2016-02-12 18:16
    关注

    Some dates would work find, and you can do it, but some dates such as anything from the 1st to the 12th of the month would be ambiguous since you could not tell the difference between the month and the day. If you allow two digit years you have an issue with year's 2001 to 2012 as well - AND years 2001 to 2031 with years conflicting with months.

    You could ask the user to clarify in certain situations, but that is even more complication.

    Don't forget to add:

        $todate = stripslashes(trim($_POST['form-todate']));
    

    To kill any potential SQL injections.

    Also here is a date validation:

        function validateDate($date, $format = 'Y-m-d H:i:s') {
            $d = DateTime::createFromFormat($format, $date);
            return $d && $d->format($format) == $date;
        }
    

    function was copied from this answer or php.net

    You can pass the input string to this function with various formats until one or more matches (you probably don't want the time in there so take it out).

    If there is more than one format matching - query the user to confirm which one.

    By the way if you are webifying this there is a great bootstrap js technique I have used at (i think) https://eonasdan.github.io/bootstrap-datetimepicker/

    It makes a mini calendar on your input field so the users don't have to type anything - just point and click.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题