Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate date? I have of Days + Start Date and Find end Date

I am developing android application, in that application How to calculate the end date based on Start Date and No of days?E.g I have starting date Sep 13, 2012 if i add 45 days with that date I will get 27 October 2012.

How to do that?

I cannot use the date function inside if statement.

My code:

f (resCrop.equals("Paddy")) {

    if(rescultivation1.equals("Conventional method - Delta"))
        {
            if(resvariety1.equals("Short duration"))
            {
                WA.setVisibility(View.VISIBLE);
                TONE.setVisibility(View.VISIBLE);
                TTWO.setVisibility(View.VISIBLE);
                TTHREE.setVisibility(View.VISIBLE);
                //date calculation
                        SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
                Calendar c1 = Calendar.getInstance(); // Get Calendar Instance
            try {
                c1.setTime(sdf.parse(resDate));
                } catch (ParseException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                c1.add(Calendar.DATE, 3);  // add 3 days
                sdf = new SimpleDateFormat("dd-M-yyyy");

          Date resultdate = new Date(c1.getTimeInMillis());   // Get new time 
          String dateInString = sdf.format(resultdate);
          WP.setText(dateInString);
          WP.setEnabled(false);
          Calendar c2 = Calendar.getInstance();
          c2.add(Calendar.DATE, 35);  // add 45 days
          sdf = new SimpleDateFormat("dd-M-yyyy");
            }
        }
     }

Its not working inside the if statement. if i used outside if its working fine. how to resolve this problem. please advice me.

like image 891
Madhan Shanmugam Avatar asked Dec 06 '25 08:12

Madhan Shanmugam


1 Answers

Try this code . You can use any date format what you want.

    String dateInString = "2011-09-13";  // Start date
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Calendar c = Calendar.getInstance(); // Get Calendar Instance
    c.setTime(sdf.parse(dateInString));

    c.add(Calendar.DATE, 45);  // add 45 days
    sdf = new SimpleDateFormat("MM/dd/yyyy");

    Date resultdate = new Date(c.getTimeInMillis());   // Get new time 
    dateInString = sdf.format(resultdate);
    System.out.println("String date:"+dateInString);
like image 77
Chirag Avatar answered Dec 07 '25 21:12

Chirag