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

214
Views
Obtenga un bloque de filas con createTextFinder() de la columna A con fechas con la misma M e Y cuando la configuración regional es en_US

Tengo una hoja donde la columna A tiene fechas. Necesito obtener el número de fila de un bloque de filas con el mismo mes y año. Si la configuración regional de la hoja de cálculo es en_US , entonces el formato de fecha es similar a:

"M/d/YYYY"

Así que d está entre M e Y Como puedes ver:

 var getDayMonthYear = Utilities.formatDate(rowBlock, Session.getScriptTimeZone(), "M/d/YYYY");

Entonces, para definir el bloque de filas, necesito buscar/filtrar de la columna A todas las filas con fecha como M/YYYY . Esto es fácil de hacer con la configuración regional como por ej. en_GB donde el formato de fecha es dd/MM/YYYY . Aquí solo busco MM/YYYY sin errores.

Pero debido a que en en_US la d está entre M e Y que es M/d/YYYY , siempre recibo un error:

Exception: The parameters (null,number) don't match the method signature for SpreadsheetApp.Sheet.getRowGroup.

Lo intenté:

 Utilities.formatDate(rowBlock, Session.getScriptTimeZone(), "M,yyyy").split(",");

me sale el mismo error:

Exception: The parameters (null,number) don't match the method signature for SpreadsheetApp.Sheet.getRowGroup.

Así que este es un ejemplo del código que tengo. Funciona bien si la configuración regional de SpreadSheet está configurada en Reino Unido, que es en_GB :

 function testTimeFormat() { var logSheetNameYR = "LOG"; var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetNameYR); var rowBlock = sheet.getRange(sheet.getLastRow() - 1, 1).getValue(); var getMonthYear = Utilities.formatDate(rowBlock, Session.getScriptTimeZone(), "MM/YYYY"); var cells = sheet.getRange("A5:A").createTextFinder(getMonthYear).findAll().map(x => x.getRowIndex()); var firstRowOfBlock = cells[0]; console.log(firstRowOfBlock); }

Pero cuando la configuración regional es en_US, no funciona.

¿Cómo puedo hacer lo mismo cuando la configuración regional es Estados Unidos en_US o cualquier otro formato de fecha que separe M de Y con d o cualquier otro carácter intermedio?

Archivo de prueba:

https://docs.google.com/spreadsheets/d/1ExXtmQ8nyuV1o_UtabVJ-TifIbORItFMWjtN6ZlruWc/edit?usp=sharing

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

0

createTextFinder no será ideal para esto porque este método solo funcionará en los valores de texto exactos que se muestran en cada celda del rango A5:A en su hoja.

Recomendación

Puede probar este script de muestra a continuación usando la manipulación de cadenas de la matriz. Esto devolverá las filas de todas las celdas que coincidan con getMonthYear en el rango A5:A :

Guión de muestra:

 function test(){ var logSheetNameYR = "LOG"; var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(logSheetNameYR); var rowBlock = sheet.getRange(sheet.getLastRow() - 1, 1).getValue(); var getMonthYear = Utilities.formatDate(rowBlock, "GMT+1", "MM/yyyy"); //using UK timezone var range = sheet.getRange("A5:A"); var startRow = range.getRow(); var cells = range.getValues().map((x,i) => x.concat(i + startRow)) .filter(x => getMonthYear == ("0" + (new Date(x[0]).getMonth() + 1)).slice(-2) + "/" + new Date(x[0]).getFullYear()) .map(x => x[1]); Logger.log(cells); }

Resultado de la muestra:

ingrese la descripción de la imagen aquí

Sábana:

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza Report

0

Así que terminé renunciando a los trucos del buscador de texto y seguí la sugerencia de @ASyntuBU y usé su código con un cambio en la parte de return usando AND que es && para separar d de m de y de esta manera el filtro no impondrá un orden particular como dd/MM/YYYY pero devolverá a una matriz todos los números de fila con celdas en la columna A que cumplen las condiciones independientemente del orden, formato de fecha, etc. Al menos creo que eso es lo que hace. ¡Gracias @ASyntuBU!

 // Used for getting the arrays with blocks of rows of `d`+ `m`+ `y` let range = sheet.getRange("A5:A"); let startRow = range.getRow(); let [y, m, d] = Utilities.formatDate(new Date(), timeZone, "yyyy,MM,dd").split(","); let cells = range.getValues().map((x, i) => x.concat(i + startRow)).filter(x => { // filter "dd" let date = new Date(x[0]); let day = date.getDate(); let month = ("0" + (date.getMonth() + 1)).slice(-2); let year = date.getFullYear(); return (`${d}` === `${day}` && `${m}` === `${month}` && `${y}` === `${year}`) }).map(x => x[1]);

Cuando quiero agrupar por mes, el return será:

 return (`${m}` === `${month}` && `${y}` === `${year}`)

Y por grupo por año:

 return (`${y}` === `${year}`)

Esto devuelve los números de fila en una matriz, luego obtenemos la posición 0 (primera) con cells[0] para encontrar el número de fila donde se colocará el identificador de grupo.

about 4 years ago · Juan Pablo Isaza Report

0

No necesita especificar el formato, solo necesita obtener los detalles por separado (día, mes, año) para facilitar la comparación.

Otra cosa a tener en cuenta, nunca sacrifiques la legibilidad por un código más corto. Use variables si es necesario.

 // get all details of the date var mmddyyyy = Utilities.formatDate(rowBlock, "GMT+1", "MM/dd/yyyy"); //using UK timezone // split to each category for easier access var [mm, dd, yyyy] = mmddyyyy.split('/'); var range = sheet.getRange("A5:A"); var startRow = range.getRow(); var cells = range.getValues().map((x,i) => x.concat(i + startRow)) .filter(x => { var date = new Date(x[0]); var month = ("0" + (date.getMonth() + 1)).slice(-2); var year = date.getFullYear(); var day = date.getDate(); // date properties are always the same on different formats // because these are outputs of date methods // just create a combination of the variables // eg you want to match the exact date return (`${dd}${mm}${yyyy}` == `${day}${month}${year}`) }) .map(x => x[1]);

ingrese la descripción de la imagen aquí

ingrese la descripción de la imagen aquí

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!