【问题标题】:Regex to reorder parts of date in javascript正则表达式在javascript中重新排序部分日期
【发布时间】:2021-12-03 09:57:33
【问题描述】:

我有一个日期和该日期的格式,由用户提供。 (本示例使用 d.m.yyyy 和 15.10.2021)

从那个格式,我需要得到年月日的位置,这样我就可以在日期上使用那个位置了。

const year = /y{4}|y{2}/.exec(format);
const month = /m{1,2}/.exec(format);
const day = /d{1,2}/.exec(format);

const yearVal = date.substring(year.index, year.index + year[0].length);

问题在于格式有 1 个字母,但我的日期有 2 个数字。 (d 和 15。)所以我得到 0.20 而不是 2021 我如何更改它以使用所有不同的格式?

您可以在此处查看所有可能的格式:node-dateformat

例如:“d”和“dd”的区别是这样的:

"d" 以数字表示的月份中的日期;个位数天数没有前导零。

"dd" 以数字表示的月份中的日期;个位数天数前导零。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以像这样从模式生成正则表达式:

    format.replace(/([ymd])\1*/g, (match, ymd) => `(?<${ymd}>${'\\d'.repeat(match.length)})`);
    

    yyyy-mm-dd 将变为/(&lt;?y&gt;\d\d\d\d)-(&lt;?m&gt;\d\d)-(&lt;?d&gt;\d\d)/,然后您可以使用组名提取年/月/日:

    function getDates(format, date) {
      const regex = new RegExp(format.replace(/(\w)\1+|(\w)/g, ({length}, w, s) => `(?<${w||s}>${s ? '\\d+' : '\\d'.repeat(length)})`));
      const result = date.match(regex);
      if(result) {
        const { y: year, m: month, d: day } = result.groups;
        return { year, month, day };
      }
    }
    
    
    console.log(getDates('yyyy-mm-dd', '2021-10-15'));
    console.log(getDates('dd/mm/yyyy', '15/10/2021'));
    console.log(getDates('mm-dd-yy', '10-15-21'));
    
    console.log('----');
    
    console.log(getDates('yyyy-m-d', '2021-9-15'));
    console.log(getDates('yyyy-m-d', '2021-10-6'));

    【讨论】:

    • 最后一种情况有一个有趣的问题,当年份转换为 Date 对象时,年份被假定为 1921 而不是 2021。
    • @Jesper Computers 不知道如何解决歧义。年份21 可能意味着任何十年。所以最好使用一整年,或者手动将两位数的年份转换为四位数字以避免歧义,如果它只有两位数,则在其前面放置一个20
    • 这似乎不适用于任何一位数日期。
    • @Jesper 确保格式与输入匹配。 yyyy-mm-dd 不能匹配 2021-9-31,必须是 2021-09-30
    • @Jesper 我弄错了,yyyy-m-d 应该匹配 2020-10-10,因为不可能用一个数字来表示十月。我刚刚更新了我的解决方案来解决这个问题。
    【解决方案2】:

    这里的另一个选项来拆分格式和值,在各个索引处查找 y/m/d

    const lookup = ( format, value ) => {
        const f = format.split(/(m+|d+|y+)/).filter(Boolean);
        const v = value.split(/(\D+)/).filter(Boolean);
        return [
            v[f.findIndex(i => i.startsWith('y'))],
            v[f.findIndex(i => i.startsWith('m'))],
            v[f.findIndex(i => i.startsWith('d'))]
        ];
    }
    console.log(lookup('d.m.yyyy', '10.5.2021'));
    console.log(lookup('d.m.yyyy', '10.12.2021'));
    console.log(lookup('dd.mm.yyyy', '10.05.2021'));
    

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      相关资源
      最近更新 更多