How to get Date in the same format as String

2019-01-15 23:03发布

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.

2条回答
不美不萌又怎样
2楼-- · 2019-01-15 23:45

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

查看更多
▲ chillily
3楼-- · 2019-01-15 23:55

You can try as this:

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

    //for testing
    System.out.println(news);
查看更多
登录 后发表回答