如何在 Javascript 中获取当前格式化的日期 dd/mm/yyyy 并将其附加到输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12409299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current formatted date dd/mm/yyyy in Javascript and append it to an input
提问by VolosBlur
I would like to add a current date to a hidden HTML tag so that it can be sent to the server:
我想将当前日期添加到隐藏的 HTML 标记中,以便将其发送到服务器:
<input type="hidden" id="DATE" name="DATE" value="WOULD_LIKE_TO_ADD_DATE_HERE">
How can I add a formatted date to the VALUE attribute?
如何向 VALUE 属性添加格式化日期?
回答by Aelios
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
let dateObj = new Date();
let month = monthNames[dateObj.getMonth()];
let day = String(dateObj.getDate()).padStart(2, '0');
let year = dateObj.getFullYear();
let output = month + '\n'+ day + ',' + year;
document.querySelector('.date').textContent = output;
回答by Ali
I honestly suggest that you use moment.js. Just download moment.min.js
and then use this snippet to get your date in whatever format you want:
老实说,我建议您使用moment.js。只需下载moment.min.js
并使用此代码段以您想要的任何格式获取您的日期:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
对日期格式使用以下图表:
回答by Varun Natraaj
<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>
回答by Wutz
To get current date/time in javascript:
要在 javascript 中获取当前日期/时间:
var date = new Date();
If you need milliseconds for easy server-side interpretation use
如果您需要毫秒来轻松进行服务器端解释,请使用
var value = date.getTime();
For formatting dates into a user readable string see this
要将日期格式化为用户可读的字符串,请参阅此
Then just write to hidden field:
然后只需写入隐藏字段:
document.getElementById("DATE").value = value;
回答by Asciiom
By using the value attribute:
通过使用 value 属性:
var today = new Date();
document.getElementById('DATE').value += today;
回答by Bart Friederichs
Use the DOM's getElementByid
method:
使用 DOM 的getElementByid
方法:
document.getElementById("DATE").value = "your date";
document.getElementById("DATE").value = "your date";
A date can be made with the Date
class:
可以与Date
班级进行约会:
d = new Date();
d = new Date();
(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)
(提示:在 Chrome 或 Firefox 的 Firebug 扩展程序中安装一个 javascript 控制台。它使您能够使用 DOM 和 Javascript)
回答by Rocket Hazmat
You edit an element's value
by editing it's .value
property.
您可以value
通过编辑元素的.value
属性来编辑元素的。
document.getElementById('DATE').value = 'New Value';