Search code examples
javanumberformatexception

How to get the next date using java with present date as input


For my need, I have to update the date to the next day given I have the current date

The method I am using to get the current date


       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
        return sdf.format(new Date());

Now I want to get the next date using this as input I tried this

  System.out.println(Integer.parseInt(getOrderDate())+1);

I am getting this error

java.lang.NumberFormatException: For input string: "2020-01-06T09:46:29-0400

Can someone help and let me know.


Solution

  • You have to add the day where you set the date :

        return sdf.format(new Date());
    

    To do so, you can have a method like :

    public String getOrderDate(Integer daysToAdd) {
        // Date computation
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        if(daysToAdd!=null) {
           c.add(Calendar.DATE, daysToAdd);
        }
        // Date formatting
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
        return sdf.format(c.getTime());
    }