0

I want to get the Date object which contains Date in the form yyyy-mm-dd after adding few months to existing Date object. Using DateFormat object I have tried this way but its not giving the output as I want. How can I get this Date format in Java? My code-

         Calendar c=Calendar.getInstance();

        DateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
            Date d=cal.getTime();
            c.add(Calendar.MONTH,10);
            Date newd1=c.getTime();
            String news=sdf.format(newd1);
            Date dnew=(Date)sdf.parse(news);

String news has the date of format yyyy-mm-dd but when I use parse on that String it results Date object which is of format "Thu Jan 21 00:14:00 IST 2016". How can I get the Date object in the form of "yyyy-mm-dd" using String news in the above code.

user1
  • 31
  • 6
  • You will want to tag the question with the language you are using. – Dijkgraaf May 20 '15 at 20:53
  • I am using Java.. n i hv tagged nw – user1 May 20 '15 at 20:54
  • 3
    Read the documentation of SimpleDateFormat. It explains what `mm` means. Hint: it doesn't mean "month". Note that a Date doesn't have any format. It's just a number of milliseconds. You can choose how to transform this number of milliseconds to a string by using a DateFormat with the appropriate pattern. Your code doesn't make much sense. – JB Nizet May 20 '15 at 20:54
  • It means "minute in hour", I just read.. – user1 May 20 '15 at 20:57
  • 1
    A `Date` does not have a format. – Sotirios Delimanolis May 20 '15 at 21:04
  • also a duplicate of [change the date format](http://stackoverflow.com/questions/17958062/change-the-date-format) / [Change date format](http://stackoverflow.com/questions/16805762/change-date-format) / [change Date format in java?](http://stackoverflow.com/questions/12934740/change-date-format-in-java) / [Change Date format Java](http://stackoverflow.com/questions/15504378/change-date-format-java) and many other instances of the same question. – Jesper May 20 '15 at 21:05

2 Answers2

1

java.util.Date doesn't have format. Its just Date.

You can make it print its values in any form you want, by using SimpleDateFormat

Mecon
  • 977
  • 1
  • 6
  • 17
0

You can try as this:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String news = sdf.format(new Date());

    //for testing
    System.out.println(news);
Andritchi Alexei
  • 1,380
  • 1
  • 16
  • 23