patternjavaMinor
Java loop extracting month and year between two dates
Viewed 0 times
yeardatesloopjavatwobetweenmonthextractingand
Problem
I have a
I have to create a new entity
I have 2 questions:
ContratMercan with 2 Timestamps containing start and end dates. I have to create a new entity
SeguimientoSeccion for each month between this 2 dates.I have 2 questions:
- There is a way to improve it?
- After this I will need to manipulate the
List seccionesto see which one matches other entity... I though about making aMapbut there can be 2 or more sections in eachmonthandyear
private List createSectionsPerMonth(ContratMercan contrato)
{
List secciones = new ArrayList();
Calendar start = Calendar.getInstance();
start.setTime(contrato.getPeriodoEntregaIni());
start.set(Calendar.DAY_OF_MONTH, 1);
Calendar end = Calendar.getInstance();
end.setTime(contrato.getPeriodoEntregaFin());
end.set(Calendar.DAY_OF_MONTH, 2); // for loop comparison
for (int month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR); start.before(end); month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR)) {
SeguimientoSeccion seccion = new SeguimientoSeccion();
seccion.setMonth(month + 1); // natural month number
seccion.setYear(year);
start.add(Calendar.MONTH, 1);
secciones.add(seccion);
}
return secciones;
}Solution
The code would be simpler if you used a
Consider implementing a
Calendar object as the loop variable.Calendar current = …;
Calendar end = …;
for (; current.before(end); current.add(Calendar.MONTH, 1)) {
SeguimientoSeccion seccion = new SeguimientoSeccion();
seccion.setMonth(1 + current.get(Calendar.MONTH)); // natural month number
seccion.setYear(current.get(Calendar.YEAR));
secciones.add(seccion);
}Consider implementing a
SeguimientoSeccion.setMonthYear(m, y) method instead, as it's probably useless to set one of the fields without also setting the other.Code Snippets
Calendar current = …;
Calendar end = …;
for (; current.before(end); current.add(Calendar.MONTH, 1)) {
SeguimientoSeccion seccion = new SeguimientoSeccion();
seccion.setMonth(1 + current.get(Calendar.MONTH)); // natural month number
seccion.setYear(current.get(Calendar.YEAR));
secciones.add(seccion);
}Context
StackExchange Code Review Q#110330, answer score: 3
Revisions (0)
No revisions yet.