diff --git a/docs/laydate/detail/options.md b/docs/laydate/detail/options.md index a8905729..612f44d3 100644 --- a/docs/laydate/detail/options.md +++ b/docs/laydate/detail/options.md @@ -170,6 +170,29 @@ format: '北京时间 H 点 m 分' +formatToDisplay 2.9.9+ + + +仅用于格式化日期显示的格式,不影响日期值 + +``` +formatToDisplay: function (value) { + // value - 日期字符串 + var date = new Date(value); + var displayValue = [ + value, + date.toLocaleDateString(Intl.LocalesArgument, { weekday: 'long' }) + ].join(' '); + return displayValue; +}; + +``` + + +function +- + + [value](#options.value) diff --git a/src/modules/laydate.js b/src/modules/laydate.js index 28b440e5..fe0d3c26 100644 --- a/src/modules/laydate.js +++ b/src/modules/laydate.js @@ -417,6 +417,19 @@ if(options.show || isStatic) that.render(); isStatic || that.events(); + // 重定义 input 元素的 get set + if(typeof options.formatToDisplay === 'function'){ + if(that.isInput(options.elem[0])){ + that.formatToDisplay(options.elem[0], options.formatToDisplay); + } else { + var rangeElem = that.rangeElem; + if(rangeElem){ + that.formatToDisplay(rangeElem[0][0], options.formatToDisplay); + that.formatToDisplay(rangeElem[1][0], options.formatToDisplay); + } + } + } + //默认赋值 if(options.value && options.isInitValue){ if(layui.type(options.value) === 'date'){ @@ -1931,6 +1944,30 @@ return this.newDate(obj).getTime(); } + /** + * 格式化输入框显示值 + * @param {HTMLInputElement} elem HTML input 元素 + * @param {(value: string) => string} displayValueCallback + */ + Class.prototype.formatToDisplay = function (elem, displayValueCallback) { + var that = this; + var props = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value'); + + Object.defineProperty( + elem, + 'value', + lay.extend({}, props, { + get: function () { + return this.getAttribute('lay-date'); + }, + set: function (value) { + props.set.call(this, displayValueCallback.call(that, value)); + this.setAttribute('lay-date', value); + }, + }) + ); + }; + //赋值 Class.prototype.setValue = function(value){ var that = this @@ -1956,7 +1993,8 @@ rangeElem[1].val(value[1] || ''); } else { if(lay(elem).find('*').length === 0){ - lay(elem).html(value); + var displayValue = typeof options.formatToDisplay === 'function' ? options.formatToDisplay(value) : value; + lay(elem).html(displayValue); } lay(elem).attr('lay-date', value); }