[英]How to change date format of date input in HTML
I created this code sample for get the date from a date picker.我创建了此代码示例以从日期选择器中获取日期。 I need to push the date value into the paragraph element as default (YYYY-MM-DD) but I need the date input to show the date as Month-dd-YY (ex: Oct-25-18)
我需要将日期值作为默认值 (YYYY-MM-DD) 推入段落元素,但我需要输入日期以将日期显示为 Month-dd-YY(例如:Oct-25-18)
<input type="date" id="date" /> <br/>
<button id="btn" onclick="show()">Ok</button><br/>
<p id="p"></p>
<script type="text/javascript">
function show(){
var x = document.getElementById('date');
x.innerHTML = x.value;
document.getElementById('p').innerHTML = x.value;
}
</script>
I tried with x.innerHTML = x.value
but not working.我试过
x.innerHTML = x.value
但不起作用。
How I can do this?我怎么能做到这一点?
Try parsing to milliseconds then to JavaScript date.尝试解析为毫秒,然后解析为 JavaScript 日期。 Something like this:
像这样的东西:
var x = document.getElementById('date');
var msec = Date.parse(x);
var d = new Date(msec);
document.getElementById("p").innerHTML = d;
Near the bottom of this page: https://www.w3schools.com/js/js_date_formats.asp在本页底部附近: https : //www.w3schools.com/js/js_date_formats.asp
You can use the code mentioned below.您可以使用下面提到的代码。 If having a hard time understanding it.
如果很难理解它。 Ping me :)
平我:)
<input type="date" id="date" /> <br/>
<button id="btn" onclick="show()">Ok</button><br/>
<p id="p"></p>
<script type="text/javascript">
function show(){
var x = document.getElementById('date');
var temp_date = new Date(x.value);
var date = temp_date.getDate();
var month = temp_date.getMonth() + 1;
var year = temp_date.getFullYear();
format_date = month + " " + date + " " + year;
x.innerHTML = x.value; // - not sure what you were trying
// to achieve but x here is input not other element.
document.getElementById('p').innerHTML = format_date;
}
You can easily do it by using CSS and js with using HTML 5 basic date type input您可以通过使用 HTML 5 基本日期类型输入使用 CSS 和 js 轻松完成
$("input").on("change", function() { this.setAttribute( "data-date", moment(this.value, "YYYY-MM-DD") .format( this.getAttribute("data-date-format") ) ) }).trigger("change")
input { position: relative; width: 150px; height: 20px; color: white; } input:before { position: absolute; top: 3px; left: 3px; content: attr(data-date); display: inline-block; color: black; } input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button { display: none; } input::-webkit-calendar-picker-indicator { position: absolute; top: 3px; right: 0; color: black; opacity: 1; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> <input type="date" data-date="" data-date-format="MMM-DD-YY" value="2020-08-29">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.