How to get Date in the same format as String

偶尔善良 提交于 2019-12-28 07:07:46

问题


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.


回答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




回答2:


You can try as this:

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

    //for testing
    System.out.println(news);


来源:https://stackoverflow.com/questions/30360089/how-to-get-date-in-the-same-format-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!