我只是试着用foreach下的格式化日期来创建一个跨度。
我有这个剧本
Date.prototype.toFormattedDate = function () {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};在html中,我尝试使用以下方法
<span class="form-control" data-bind="text: new Date(my_date).toFormattedDate() " />my_date是一个字符串日期"2020-09-13T00:00:00“。
但它总是显示南/南/南
我试图使用moment.js,但它给了我“无效日期”
演示:
Date.prototype.toFormattedDate = function() {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};
const formatted = new Date("2020-09-13T00:00:00").toFormattedDate();
console.log(formatted)
发布于 2020-05-30 18:35:23
之所以会发生这种情况,是因为my_date是一个可以观察到的。new Date(my_date)将尝试将可观察到的日期转换为日期,结果失败了。因此,通过使用my_date()获取可观测值,并在new Date()构造函数中使用它。
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13T00:00:00') })<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="text: new Date(my_date()).toFormattedDate() " />
另一个选项是为您的日期格式创建一个自定义绑定。如果不想污染Date.prototype,可以直接将所有日期格式代码移动到自定义绑定中。
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};并在span中使用绑定:
<span class="form-control" data-bind="customDateFormat: my_date" />这里有一个片段:
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13') })<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="customDateFormat: my_date" />
https://stackoverflow.com/questions/62088695
复制相似问题