Javascript在在线表单中生成时间字符串

时间:2010-12-21 20:18:09

标签: javascript string time

我有一个像这样的html表单:

<form action="https://www.123.com/cgi-bin/action" method="post">
<input type="hidden" name="item_name" value="Product Name">
<input type="hidden" name="item_number" value="Product Name_2010_12_21_15_03">
<input type="hidden" name="amount" value="29.99">
</form>

如何使用javascript用动态生成的时间字符串替换上面的“Product Name_2010_12_21_15_03”?

4 个答案:

答案 0 :(得分:0)

<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write("Product Name+" + year + "_" + month + "_" + day)
//-->
</script>

答案 1 :(得分:0)

您只需设置输入值:

<input id='product_date_time' type='hidden' name='item_number' value=''>
<script>
  document.getElementById('product_date_time').value = new Date().toString();
</script>

当然,脚本不必立即跟随输入字段。在将input元素添加到DOM之后,它必须在某个时刻运行。

如果您需要更多地控制格式,可能需要查看古老的Date.js库。

答案 2 :(得分:0)

根据您对“2010_12_21_15_03”格式的评论:

<input id='product_date_time' type='hidden' name='item_number' value=''>

<script>
function myDate () {
    var d = new Date();
    return d.getFullYear() + "_" + (d.getMonth() + 1) + "_" + d.getDate() + "_" + d.getHours() + "_" + d.getMinutes();
}

document.getElementById('product_date_time').value = myDate();
</script>

答案 3 :(得分:0)

好的,我明白了:

    <form action="https://www.123.com/cgi-bin/action" method="post" name="My_Form">
      <input type="hidden" name="item_name" value="Product_Name">
      <input type="hidden" name="item_number" value="Product_Name">
      <input type="hidden" name="amount" value="9.99">
      <script type="text/javascript">
      <!--
        function getCorrectedYear(year)
        {
          year=year-0;
          if (year<70) return (2000+year);
          if (year<1900) return (1900+year);
          return year;
        }
        var today=new Date();
        var minute=today.getMinutes();
        if(minute<10) minute='0'+minute;
        var hour=today.getHours();
        if(hour<10) hour='0'+hour;
        var day=today.getDate();
        if(day<10) day='0'+day;
        var month=today.getMonth()+1;
        if(month<10) month='0'+month;
        var year=getCorrectedYear(today.getYear());
        var dateString=year+'_'+month+'_'+day+'_'+hour+'_'+minute;
        document.My_Form.item_number.value=document.My_Form.item_name.value+'_'+dateString;
      //-->
      </script>
    </form>