Dangerous Date manipulation

public static String getIncrementedDate(String someDate, int inc, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    java.util.Date initDate = null;;
    try {
      initDate = formatter.parse(someDate);
    } catch (java.text.ParseException e) {
    long Fech = initDate.getTime() + inc*24*60*60*1000;
    Date incrementedDate = new Date(Fech);
    return formatter.format(incrementedDate);

public static void main(String...strings ) throws Exception {
  System.out.println(getIncrementedDate("20081026", 1, "yyyyMMdd"));

Maybe you are expecting “20081027” output for this program? You’re wrong. This code produces “20081026”.

Changing the hour (from 3:00 AM to 2:00 AM) on 26th October involves a mathematical difference of 24 + 1 hours between 26th October and 27th October.

Don’t use java.util.Date to manipulate dates in Java. Use Calendar instead.


2 comentarios en “Dangerous Date manipulation

  1. There’s a problem relative to changing the hour.

    The difference between these two days using aritmethic on millis is 24*60*60*1000 + 1*60*60*1000 instead of 24*60*60*1000 because of this.

    It can be avoided easily using always Calendar to manipulate dates intervals.


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )


Conectando a %s