'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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | laxmy Narine |
