Calculating days between two dates with Java

前端 未结 11 1527
天命终不由人
天命终不由人 2020-11-22 04:42

I want a Java program that calculates days between two dates.

  1. Type the first date (German notation; with whitespaces: \"dd mm yyyy\")
  2. Type the second
11条回答
  •  灰色年华
    2020-11-22 05:19

    The best way, and it converts to a String as bonus ;)

    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            //Dates to compare
            String CurrentDate=  "09/24/2015";
            String FinalDate=  "09/26/2015";
    
            Date date1;
            Date date2;
    
            SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
    
            //Setting dates
            date1 = dates.parse(CurrentDate);
            date2 = dates.parse(FinalDate);
    
            //Comparing dates
            long difference = Math.abs(date1.getTime() - date2.getTime());
            long differenceDates = difference / (24 * 60 * 60 * 1000);
    
            //Convert long to String
            String dayDifference = Long.toString(differenceDates);
    
            Log.e("HERE","HERE: " + dayDifference);
        }
        catch (Exception exception) {
            Log.e("DIDN'T WORK", "exception " + exception);
        }
    }
    

提交回复
热议问题