9 changed files with 80 additions and 61 deletions
@ -0,0 +1,14 @@ |
|||||
|
import { formatDateByFmt } from "@xyx-utils/core"; |
||||
|
|
||||
|
describe("formatDateByFmt", async () => { |
||||
|
it("时间格式化", async () => { |
||||
|
const date = new Date("2025-03-07 08:54:21"); |
||||
|
expect(formatDateByFmt(date, "yyyy-MM-dd hh:mm:ss")).toStrictEqual("2025-03-07 08:54:21"); |
||||
|
}); |
||||
|
it("22", async () => { |
||||
|
const date = new Date("2025-03-07 08:02:01"); |
||||
|
expect(formatDateByFmt(date, "yyyy-MM-dd hh:m:s")).toStrictEqual("2025-03-07 08:2:1"); |
||||
|
const date2 = new Date("2025-03-07 08:12:01"); |
||||
|
expect(formatDateByFmt(date2, "yyyy-MM-dd hh:m:s")).toStrictEqual("2025-03-07 08:12:1"); |
||||
|
}); |
||||
|
}); |
@ -0,0 +1,21 @@ |
|||||
|
import { padLeftZero } from "@xyx-utils/core/common/padLeftZero"; |
||||
|
|
||||
|
export function formatDateByFmt(date, fmt) { |
||||
|
if (/(y+)/.test(fmt)) { |
||||
|
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); |
||||
|
} |
||||
|
const o = { |
||||
|
"M+": date.getMonth() + 1, |
||||
|
"d+": date.getDate(), |
||||
|
"h+": date.getHours(), |
||||
|
"m+": date.getMinutes(), |
||||
|
"s+": date.getSeconds(), |
||||
|
}; |
||||
|
for (const k in o) { |
||||
|
if (new RegExp(`(${k})`).test(fmt)) { |
||||
|
const str = o[k] + ""; |
||||
|
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str, 2)); |
||||
|
} |
||||
|
} |
||||
|
return fmt; |
||||
|
} |
@ -1,21 +1 @@ |
|||||
import { padLeftZero } from "@xyx-utils/core/common/padLeftZero"; |
export * from "./formatDateByFmt" |
||||
|
|
||||
export function formatDateByFmt(date, fmt) { |
|
||||
if (/(y+)/.test(fmt)) { |
|
||||
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); |
|
||||
} |
|
||||
const o = { |
|
||||
"M+": date.getMonth() + 1, |
|
||||
"d+": date.getDate(), |
|
||||
"h+": date.getHours(), |
|
||||
"m+": date.getMinutes(), |
|
||||
"s+": date.getSeconds(), |
|
||||
}; |
|
||||
for (const k in o) { |
|
||||
if (new RegExp(`(${k})`).test(fmt)) { |
|
||||
const str = o[k] + ""; |
|
||||
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str, 2)); |
|
||||
} |
|
||||
} |
|
||||
return fmt; |
|
||||
} |
|
Loading…
Reference in new issue