Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Cadena de formato (donde la cadena representa una sesión) en formato de fecha usando moment js

tengo un valor de variable que me da los datos como " Sesión entre el 15 de enero de 2022 a las 4:00 a. m. y el 15 de enero de 2022 a las 4:30 a. 15-01-2022 4:30 am ".

Cosas que he probado:

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

la salida de la consola es: sesión entre el 15/01/2022 a las 4:00 am y el 15/01/2022 a las 4:00 am

pero la salida requerida es Sesión entre el 15/01/2022 a las 4:00 a.m. y el 15/01/2022 a las 4:30 a.m.

Cualquier tipo de ayuda y sugerencia sería apreciada. Gracias por adelantado

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¡Bienvenido Iaxmy!

En realidad, no necesitas un momento para esto. El objeto Date aceptará el Jan 15 2022 en el constructor. Puede usar una expresión regular para extraer y reemplazar las cadenas antiguas por las nuevas.

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

La expresión regular busca: palabra, número, número, todo separado por un espacio.

También puede cambiar esta línea si desea el formato DD-MM-YYYY.

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

Editar

Como señaló RobG, la new Date(string) depende de la implementación. Así que supongo que deberías evitar y usar una biblioteca externa como moment en su lugar. En realidad, condensa bastante esta respuesta.

 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

about 4 years ago · Juan Pablo Isaza Report

0

Como sugirió @evolutionxbox, lo probé y funciona así. a continuación se muestra el código final que escribí:

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

La consola me da el resultado esperado.

Gracias a todos los que me ayudaron.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!