问题
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