How to add days into the date in android

前端 未结 10 1150
眼角桃花
眼角桃花 2020-12-01 12:07

In my database I am getting start date like 2011-11-30(yyyy/mm/dd)format.and duration date like 40 days.How can i calculate the days and get new date format of mm/dd/yyyy.

10条回答
  •  无人及你
    2020-12-01 12:31

    Step-1 Get Calendar instance from the specified string

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();
                c.setTime(sdf.parse(dateInString));
    

    Step-2 use add() to add number of days to calendar

    c.add(Calendar.DATE, 40); 
    

    Step-3 Convert the dtae to the resultant date format

    sdf = new SimpleDateFormat("MM/dd/yyyy");
                Date resultdate = new Date(c.getTimeInMillis());
                dateInString = sdf.format(resultdate);
    

    Source Code

    String dateInString = "2011-11-30";  // Start date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(sdf.parse(dateInString));
            c.add(Calendar.DATE, 40);  
            sdf = new SimpleDateFormat("MM/dd/yyyy");
            Date resultdate = new Date(c.getTimeInMillis());
            dateInString = sdf.format(resultdate);
            System.out.println("String date:"+dateInString);
    

提交回复
热议问题