使用 moment js 将字符串(其中字符串表示会话)格式化为日期格式

Formatting string( where string represents a session) into date format using moment js

我有一个变量 value 给我的数据是“Session between Jan 15 2022 4:00Am and Jan 15 2022 4:30Am”,我想将此日期字符串格式化为“Session between 15-01-2022 4:00Am And 15-01-2022 4:30Am".

我尝试过的事情:

//function to remove "session between and" so that the date can be parsed.
public removeUnwantedText(words : any){
        var cleanUpWords = ["Session","between","And"];
        var expStr = cleanUpWords.join("\b|\b");
        return words.replace(new RegExp(expStr, 'gi'), '').trim().replace(/ +/g, ' ');
    }
//calling the function and trying to format date string,where value="Session between Jan 15 2022 4:00Am And Jan 15 2022 4:30Am"

 console.log(moment( this.removeUnwantedText(value),"MMM DD YYYY h:mmA").format('[Session between] DD-MM-YYYY  h:mmA [And] DD-MM-YYYY  h:mmA'));

控制台输出是:2022 年 1 月 15 日 4:00Am 和 2022 年 1 月 15 日之间的会话 4:00Am

但要求的输出是 01/15/2022 4:00Am 和 01/15/2022 4:30Am

之间的会话

如有任何帮助和建议,我们将不胜感激。提前致谢

欢迎 Iaxmy!

您实际上不需要时间。 Date 对象将在构造函数中接受 Jan 15 2022。您可以使用正则表达式提取旧字符串并将其替换为新字符串。

  reformatString(string: string) {
    //Find the dates
    const matches = string.match(/[a-zA-Z]+ [0-9]+ [0-9]+/g);
    if (!matches) throw new Error('Failed to parse string');

    //Convert to new format
    const newStrings = matches.map((s) => {
      const date = new Date(s);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const year = date.getFullYear();
      return month + '/' + day + '/' + year;
    });

    //Replace with new strings
    matches.forEach(
      (match, index) => (string = string.replace(match, newStrings[index]))
    );

    return string;
  }

正则表达式搜索:单词、数字、数字,全部由 space 分隔。

如果您想要 DD-MM-YYYY 格式,也可以更改此行。

return day + '-' + month + '-' + year;

编辑

正如 RobG 所指出的,new Date(string) 取决于实现。所以我想你应该避免使用像 moment 这样的外部库。它实际上浓缩了这个答案。

  reformatString(string: string) {
    //Find the dates
    const matches = string.match(/[a-zA-Z]+ [0-9]+ [0-9]+/g);
    if (!matches) throw new Error('Failed to parse string');

    //Convert to new format
    const newStrings = matches.map((s) => {
      return moment(s, 'MMM DD YYYY').format('MM/DD/YYYY');
    });

    //Replace with new strings
    matches.forEach(
      (match, index) => (string = string.replace(match, newStrings[index]))
    );

    return string;
  }

Stackblitz:https://stackblitz.com/edit/angular-ivy-mk8ifz?file=src/app/test/test.component.ts

按照@evolutionxbox 的建议,我试了一下,效果是这样的。 下面是我写的最终代码:

//function to remove gibberish words so that the value in the description column can parse the date.
    public removeUnwantedText(words : any){
    let cleanUpWords = ["Session","between","And"];
    let expStr = cleanUpWords.join("\b|\b");
    return words.replace(new RegExp(expStr, 'gi'), '').trim().replace(/ +/g, ' ');
   }
 //splitting the description data with And as breakpoint and storing them separately
     let sessionDate = value.split('And');
     let sessionStart = sessionDate[0];
     let sessionEnd = sessionDate[1];

  //formatting the date string into DD-MM-YYYY hh:mm A format.
   let sStart = moment(this.removeUnwantedText(sessionStart),["MMM DD YYYY h:mmA"]).format('[Session between] DD-MM-YYYY  h:mmA');
   let sEnd = moment(this.removeUnwantedText(sessionEnd),["MMM DD YYYY h:mmA"]).format('[And] DD-MM-YYYY  h:mmA');
           
//concatenating both the results into one and returning the output.
       let res = sStart +' '+ sEnd; 
       console.log(res);

控制台给了我预期的输出。

感谢所有帮助过我的人。