JSP (Java Server Page) - problemas con restar una fecha

 
Vista:

problemas con restar una fecha

Publicado por jasmin (6 intervenciones) el 27/09/2006 18:02:47
Hola amigos..espero alguien me pueda ayudar a resolver un problema de restar fechas en jsp, la duda es la siguiente, por ejemplo hoy estamos a 27/09/2006(fecha1), esa fecha la tengo..pero necesito colocar 2 fechas mas en base a esa fecha1, por ejemplo:
fecha2: que tenga el ultimo dia del mes anterior a este actual(septiembre en este caso)..osea deberia quedarme :
fecha2 = 31/08/2006

fecha3: que tenga la fecha de 3 mes atras de agosto (en este caso)...osea:
fecha3: 01/06/2006..
Muchas Gracias a quien pueda ayudarme...Saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:problemas con restar una fecha

Publicado por Jesús Martín (4 intervenciones) el 28/09/2006 09:35:59
Se puede hacer (no se si será demasiado chapuza) con un switch que conste de 12 cases que evalúen el mes de la fecha que tienes y, en función del mes de esta, establezcan las otras dos.

Si no quieres hacerlo así, busca información sobre el tipo java gregorianCalendar. Sé que con este tipo puede hacerse , pero igualmente tendrás que evaluar la expresión mediante un getMonth(), por lo que la solución seguiría siendo la misma.

Un saludo, espero haberte ayudado.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:problemas con restar una fecha

Publicado por neossoftware (70 intervenciones) el 29/09/2006 23:39:28
Puedes usar esta clase para restar dos fechas:

/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Boston, MA 02111.
* */

package test.com;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import java.util.TimeZone;

/**
* Clase que se encarga de realizar la resta de dos fechas
* usando Java
* @author Mario Hidalgo Martinez
* */
public class DateDiff {
// set some constants that allow pretty accurate estimates over
// about 2,000 years before or after the present. These are
// slight overestimates since that's what we want (and need!)
private static final double DAY_MILLIS = 1000*60*60 * 24.0015;
private static final double WEEK_MILLIS = DAY_MILLIS * 7;
private static final double MONTH_MILLIS = DAY_MILLIS * 30.43675;
private static final double YEAR_MILLIS = WEEK_MILLIS * 52.2;

protected int getDateDiff( int calUnit, Date d1, Date d2 ) {
// swap if d1 later than d2
boolean neg = false;
if( d1.after(d2) ) {
Date temp = d1;
d1 = d2;
d2 = temp;
neg = true;
}

// estimate the diff. d1 is now guaranteed <= d2
int estimate = (int)getEstDiff( calUnit, d1, d2 );

// convert the Dates to GregorianCalendars
GregorianCalendar c1 = new GregorianCalendar();
c1.setTime(d1);
GregorianCalendar c2 = new GregorianCalendar();
c2.setTime(d2);

// add 2 units less than the estimate to 1st date,
// then serially add units till we exceed 2nd date
c1.add( calUnit, (int)estimate - 2 );
for( int i=estimate-1; ; i++ ) {
c1.add( calUnit, 1 );
if( c1.after(c2) )
return neg ? 1-i : i-1;
}
}

private int getEstDiff( int calUnit, Date d1, Date d2 ) {
long diff = d2.getTime() - d1.getTime();
switch (calUnit) {
case Calendar.DAY_OF_WEEK_IN_MONTH :
case Calendar.DAY_OF_MONTH :
// case Calendar.DATE : // codes to same int as DAY_OF_MONTH
return (int) (diff / DAY_MILLIS + .5);
case Calendar.WEEK_OF_YEAR :
return (int) (diff / WEEK_MILLIS + .5);
case Calendar.MONTH :
return (int) (diff / MONTH_MILLIS + .5);
case Calendar.YEAR :
return (int) (diff / YEAR_MILLIS + .5);
default:
return 0;
} /* endswitch */
}

// some test code...
public static void main(String[] args) {
String arg[] =new String[2];
arg[0]="29/9/2006";
arg[1]="1/10/2006";
args=arg;
DateDiff dd = new DateDiff();
Date then = null, now = null;
DateFormat df = DateFormat.getInstance();
DecimalFormat ddf = (DecimalFormat)NumberFormat.getInstance();
ddf.setMaximumFractionDigits(0);

// Use this instead of DecimalFormat if you have it...
// If not, you can get it at:
// http://pws.prserv.net/ad/programs/Programs.html#PaddedDecimalFormat
// PaddedDecimalFormat ddf =
// PaddedDecimalFormat.getNumberInstance(0, Locale.getDefault());

df.setTimeZone( TimeZone.getDefault() );
if (args.length < 2) {
String pattern = ((SimpleDateFormat)df).toLocalizedPattern();

System.out.println("Usage: Enter two dates in this format: "
+ pattern.substring( 0, pattern.indexOf(' ')) );
System.exit(0);
} else {
try {
then = df.parse( args[0] + " 12:00 PM" );
now = df.parse( args[1] + " 12:00 PM" );
} catch ( ParseException e ) {
System.out.println("Couldn't parse date: " + e );
System.exit(1);
} /* endcatch */
} /* endif */

// now we have two Date objects. get real & estimated diff
int diff = dd.getDateDiff( Calendar.DATE, then, now );
System.out.println("Interval in days: "
//+ ddf.format( diff, 20 ) );
+ddf.format( diff ) );
diff = dd.getDateDiff( Calendar.WEEK_OF_YEAR, then, now );
System.out.println("Interval in weeks: "
// + ddf.format( diff, 20 ) );
+ ddf.format( diff ) );
diff = dd.getDateDiff( Calendar.MONTH, then, now );
System.out.println("Interval in months: "
// + ddf.format( diff, 20 ) );
+ ddf.format( diff ) );
diff = dd.getDateDiff( Calendar.YEAR, then, now );
System.out.println("Interval in years: "
// + ddf.format( diff, 20 ) );

+ ddf.format( diff ) );
}
}

o bien puedes usar GregorianCalendar para restar dias, meses años, etc.

Saludos Comunidad Open Source
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Excelnte post

Publicado por Julio Padron (1 intervención) el 13/08/2008 22:25:10
Un millon de gracias la clase funciona a la perfeccion
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar