我从WebAPI收到一个具有此属性的JSON对象:
"BirthDate": "2018-02-14T15:24:17.8177428-03:00",
HTML:
<input type="date" v-model="BirthDate" />
我使用VueJS绑定该对象,但是 VueJS在控制台中提供此消息:
The specified value "2018-02-14T15:24:17.8177428-03:00" does not conform to the required format, "yyyy-MM-dd".
在这种情况下,唯一相关的部分是2018-02-14,我可以丢弃其他信息。
我尝试创建一个双向过滤器,将日期时间转换为所需的格式,但没有成功。见VueJS two way filter
如何将日期/时间格式转换并绑定到HTML日期输入所需的日期格式?
答案 0 :(得分:4)
考虑complex_model()
是您的财产,您可以使用:
return
自myDate
is only syntactic sugar to :value
and @input
以来,您可以使用它们。在这种情况下,我们使用并稍微更改了它们(将<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
@input="myDate = $event.target.valueAsDate">
格式化为日期输入到v-model
对象的输出,反之亦然。)
检查演示,并在下方提出警告。
String
Date
答案 1 :(得分:1)
我认为这与vueJs无关,输入type="date"
期望YYYY-MM-DD格式的日期,或者为空
见这里:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date,
如果将日期对象拆分为日期和时间字段
会更好答案 2 :(得分:0)
纠正@acdcjunior,因为它不应在一天之内关闭
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
myDate: new Date('2011-04-11T10:20:30Z')
},
methods: {
setMyDateToToday() {
this.myDate = new Date();
},
addADayToMyDate() {
if (this.myDate) // as myDate can be null
// you have to set the this.myDate again, so vue can detect it changed
// this is not a caveat of this specific solution, but of any binding of dates
this.myDate = new Date(this.myDate.setDate(this.myDate.getDate() + 1));
},
getDateClean(currDate) {
// need to convert to UTC to get working input filter
console.log(currDate);
let month = currDate.getUTCMonth() + 1;
if (month < 10) month = "0" + month;
let day = currDate.getUTCDate();
if (day < 10) day = "0" + day;
const dateStr =
currDate.getUTCFullYear() + "-" + month + "-" + day + "T00:00:00";
console.log(dateStr);
const d = new Date(dateStr);
console.log(d);
return d;
}
}
});
// Notes:
// We use `myDate && myDate.toISOString().split('T')[0]` instead
// of just `myDate.toISOString().split('T')[0]` because `myDate` can be null.
// the date to string conversion myDate.toISOString().split('T')[0] may
// have timezone caveats. See: https://stackoverflow.com/a/29774197/1850609
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
@input="myDate = getDateClean($event.target.valueAsDate)">
<p>
<code>
myDate: {{ myDate }}</code>
</p>
<button @click="setMyDateToToday">Set date one to today</button>
<button @click="addADayToMyDate">Add a day to my date</button>
</div>