简体   繁体   English

在JavaScript中读取HTML5日期

[英]Reading an HTML5 date in JavaScript

I have an input field in my project that uses the HTML5 date input type. 我的项目中有一个使用HTML5日期输入类型的输入字段。 This is saved to my database in the format YYYY-MM-DD. 这以YYYY-MM-DD格式保存到我的数据库中。 In another page, I access this date from a Twig and print it in a table. 在另一页中,我从树枝上访问该日期并将其打印在表格中。 This prints in the format YYYY-MM-DD. 打印格式为YYYY-MM-DD。 So far so good. 到现在为止还挺好。 However, when I try to use an alert box to print the same date, JavaScript parses the date incorrectly to just show the year (and the wrong year at that). 但是,当我尝试使用警报框打印相同的日期时,JavaScript错误地解析了日期,从而仅显示了年份(以及错误的年份)。

Input field (as part of a bigger "make plan" input form): 输入字段(作为更大的“制定计划”输入表单的一部分):

<input type="date" id="start" name="startdate" class="form-control" required="required"/>

Output: 输出:

<td>{{plan.startdate}}</td> <!-- This prints correctly YYYY-MM-DD -->

<td>
    <script>
        alert({{plan.startdate}});   <!-- This alerts incorrectly YYYY -->                    
    </script>
</td>

I can't really see the correlation between the dates either. 我也看不到日期之间的相关性。 2014-03-27 gives '1984' in the alert box 2014-03-20 gives '1991' in the alert box 2014-04-01 gives '2009' in the alert box 2014-03-27在警报框中输入'1984'2014-03-20在警报框中输入'1991'2014-04-01在警报框中输入'2009'

I've tried to parse the date using the JavaScript, but I'm not really sure how to parse an incorrect year. 我尝试使用JavaScript解析日期,但是我不确定如何解析错误的年份。

It is being evaluated as an expression instead of a date string. 它被评估为表达式而不是日期字符串。 If you put the date in quotation marks then it should be fine. 如果将日期放在引号中,那应该没问题。 See the following 见以下

<td>{{plan.startdate}}</td> <!-- This prints correctly YYYY-MM-DD -->

<td>
    <script>
        alert("{{plan.startdate}}");   <!-- This alerts incorrectly YYYY -->                    
    </script>
</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM