From e029605793968d3e60d4332c4517bed5f9622610 Mon Sep 17 00:00:00 2001 From: morning-star <26325820+Sight-wcg@users.noreply.github.com> Date: Mon, 10 Mar 2025 14:32:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(util):=20`util.toDateString`=20=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E5=8C=96=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=20(#2543)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/util.html | 10 ++++++++++ src/modules/util.js | 33 +++++++++++++++++++++++++++++---- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/examples/util.html b/examples/util.html index 09ef0182..90f5440f 100644 --- a/examples/util.html +++ b/examples/util.html @@ -217,6 +217,16 @@ layui.use(['lay', 'util', 'layer'], function(){ toDateString($('#test2').val()) }, 50) + console.log(util.toDateString('2025-3-8 12:30:00') === '2025-03-08 12:30:00'); + console.log(util.toDateString('2025-03-08 12:30:00') === '2025-03-08 12:30:00'); + console.log(util.toDateString('2025-03-08') === '2025-03-08 00:00:00'); + console.log(util.toDateString('2025-3-8') === '2025-03-08 00:00:00'); + console.log(util.toDateString('2025-3') === '2025-03-01 00:00:00'); + console.log(util.toDateString(null) === ''); + console.log(util.toDateString(undefined) === util.toDateString(new Date())); + console.log(util.toDateString('') === ''); + console.log(util.toDateString('2025/3/8 12:30:00') === '2025-03-08 12:30:00'); + console.log(util.toDateString('2025/3/8') === '2025-03-08 00:00:00'); }); diff --git a/src/modules/util.js b/src/modules/util.js index 7fb37649..5d975592 100644 --- a/src/modules/util.js +++ b/src/modules/util.js @@ -261,11 +261,36 @@ layui.define('jquery', function(exports){ // 引用自 dayjs // https://github.com/iamkun/dayjs/blob/v1.11.9/src/constant.js#L30 var REGEX_FORMAT = /\[([^\]]+)]|y{1,4}|M{1,2}|d{1,2}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|SSS/g; + var REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i; var that = this; - var date = new Date(function(){ - if(!time) return; - return isNaN(time) ? time : (typeof time === 'string' ? parseInt(time) : time) - }() || new Date()) + + var normalizeDate = function(date) { + if(typeof date === 'undefined'){ + return new Date(); + } + if(!isNaN(date)){ + return new Date(typeof date === 'string' ? parseInt(date) : date); + } + if(typeof date === 'string' && !/Z$/i.test(date)){ + var d = date.match(REGEX_PARSE); + if(d){ + var m = d[2] - 1 || 0; + var ms = (d[7] || '0').substring(0, 3); + return new Date( + d[1], + m, + d[3] || 1, + d[4] || 0, + d[5] || 0, + d[6] || 0, + ms + ); + } + } + + return new Date(date) + } + var date = normalizeDate(time); if(!date.getDate()) return hint.error('Invalid millisecond for "util.toDateString(millisecond)"'), '';