0

I have a requirement like calculating remaining days between two-dates. It is working fine for me. but the problem is when i sent the build to UK, there it is displaying one day less compare to India(ex: India :215 days but in UK:214 days). I am using the below code:

public static int noOfDays(String currDate, String tarDate){
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date date1 = null;
    Date date2 = null;

    try {
        date1 = sdf.parse(currDate);
        date2 = sdf.parse(tarDate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return (int)( (date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24));
}   

For getting current date:

public static String getcurrentdate()
{
    Calendar now = Calendar.getInstance();

    int month = now.get(Calendar.MONTH) + 1;
    int year = now.get(Calendar.YEAR);
    int day = now.get(Calendar.DATE);
    return day+"/"+month+"/"+year;
}

And i believe that Calendar now = Calendar.getInstance(); will gives the Local time Zone instance only.if it is right then it should give same result in any location.but the result seems different. Please help me to resolve this issue.

Thanks, Ganesh

Ganesh
  • 662
  • 3
  • 8
  • 26

3 Answers3

1

When store and do time calculations, you should store all timestamps in UTC. Then explicitly set Timezone to UTC.
If you have to display local time on a display, you have to transform the Utc timestamps immedeatly before displaying, do not store localtime in the Database.
If you need localtime, you need to store an additional timezone info together with your utc time.

AlexWien
  • 28,470
  • 6
  • 53
  • 83
1

you need to set the TimeZone of Calender class. You can do so by writing :

Calender.setTimeZone(timeZone);

you can get the TimeZone of the location where the app is running by using this:

TimeZone.getDefault();
Misha Bhardwaj
  • 1,377
  • 10
  • 14
0

Use JodaTime library for date calculations and always store date s in UTC.

Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42