laxmy Narine
laxmy Narine

Reputation: 38

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

i have a variable value that is giving me the data as "Session between Jan 15 2022 4:00Am And Jan 15 2022 4:30Am", i want to format this date string into "Session between 15-01-2022 4:00Am And 15-01-2022 4:30Am".

Things i have tried:

//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'));

the console ouptut is : Session between 01/15/2022 4:00Am And 01/15/2022 4:00Am

but the required output is Session between 01/15/2022 4:00Am And 01/15/2022 4:30Am

Any kind of help and suggestions would be appreciated. Thanks in advance

Upvotes: 0

Views: 151

Answers (2)

Chris Hamilton
Chris Hamilton

Reputation: 10984

Welcome Iaxmy!

You don't actually need moment for this. The Date object will accept Jan 15 2022 in the constructor. You can use a regex to extract and replace the old strings with the new ones.

  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;
  }

The regex searches for: word, number, number, all separated by a space.

You can also change this line if you wanted the DD-MM-YYYY format.

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

Edit

As pointed out by RobG, new Date(string) is implementation dependent. So I suppose you should avoid and use an external library like moment instead. It actually condenses this answer quite a bit.

  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

Upvotes: 1

laxmy Narine
laxmy Narine

Reputation: 38

As suggested by @evolutionxbox, I tried it out and it works like that. below is the final code I wrote :

//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);

The console gives me the expected output.

Thanks to everyone who helped me.

Upvotes: 0

Related Questions