在JS中从日期字符串或UNIX时间戳提取对应日期格式pattern的方案
可用JS库方案
以下是两个开箱即用的成熟方案,无需自行编写正则匹配逻辑:
方案1:date-fns 生态的 @date-fns/parse-format 模块
- 专门用于识别输入日期字符串/时间戳对应的格式pattern,是目前同类型工具中识别准确率最高的轻量方案
- 用法示例:
import { parseFormat } from '@date-fns/parse-format' // 日期字符串输入 parseFormat('2021-08-14') // 返回 'yyyy-MM-dd' parseFormat('14-08-2021') // 返回 'dd-MM-yyyy' parseFormat('2021/08/14 16:20:00') // 返回 'yyyy/MM/dd HH:mm:ss' // Unix时间戳输入 // 可通过配置参数指定时间戳单位(秒/毫秒),返回对应的输出格式,也可搭配date-fns的format方法自定义输出规则 parseFormat(1628908800000)
- 优势:无额外冗余依赖、支持自定义歧义日期(如
03-04-2024)的识别优先级,适配不同区域的日期书写习惯
方案2:dayjs 插件 dayjs-date-pattern-guesser
- 适合已经在项目中使用dayjs的场景,插件体积小于3KB
- 用法示例:
import dayjs from 'dayjs' import datePatternGuesser from 'dayjs-date-pattern-guesser' dayjs.extend(datePatternGuesser) dayjs.guessFormat('2021-08-14') // 返回 'YYYY-MM-DD' dayjs.guessFormat('14/08/2021') // 返回 'DD/MM/YYYY'
内容的提问来源于stack exchange,提问作者user3546665
相关产品推荐
相关产品推荐

