0

I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".

1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?

2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10. Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.

How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.

Thanks in advance Omkar Ghaisas

omkar.ghaisas
  • 235
  • 5
  • 19

1 Answers1

1

To parse your date from text format:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");

More info : SimpleDateFormat doc

To substract days from your date:

public static Date substractDays(Date date, int days)
{
    long millis = date.getTime();
    long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
    //                       1milli  1s   1m   1h   1d
    return new Date(millis-toSubstract);
}

Adding some days would be the same, except replace - with +

To get back a String representation from a Date object:

DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());

EDIT:

You could also do the Date adding/substracting with the method you suggested:

public static Date substractDays(Date date, int days)
{
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -20 /*or +10*/); 
    return calendar.getTime();
}

If you want to check if a Date is in an interval, then:

public static boolean isInInterval(Date date, Date from, Date to)
{
    return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
  • The 2nd question simply means, I would like to check if my current system date falls between the excelMinus20 and excelPlus10 dates, in which case I would take appropriate action in code as per the business logic. Also, I have seen that using days * 1000 * 60 * 60 * 60 * 24; gives incorrect results some times and hence I have used the Calendar.add(Day_Of_Year,-20) to subtract date - 20 days. Let me know, if that is fine. – omkar.ghaisas Sep 16 '12 at 13:54
  • Hello! I've never had any problems with counting milliseconds manually, but you might be right. If so, then see my updated answer. – Balázs Édes Sep 16 '12 at 14:22