我创建了此代码示例,以从日期选择器获取日期。我需要将日期值作为默认值(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>
我尝试过x.innerHTML = x.value
,但是没有用。
我该怎么做?
答案 0 :(得分:0)
尝试解析为毫秒然后解析为JavaScript日期。像这样:
var x = document.getElementById('date');
var msec = Date.parse(x);
var d = new Date(msec);
document.getElementById("p").innerHTML = d;
答案 1 :(得分:0)
您可以使用下面提到的代码。如果很难理解它。给我Ping:)
<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;
}
答案 2 :(得分:0)
通过使用CSS和js以及HTML 5基本日期类型输入,您可以轻松地做到这一点
$("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">