Java Formatting Date

橙三吉。 提交于 2019-12-12 17:05:09

问题


I am trying to get the current date and format it however i am getting an invalid month of 59. Under is the code

Code

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Date todayDate = new Date();

String formatDate = df.format(todayDate);

Output is 2013-59-07


回答1:


You need "MM" for month. "mm" is for minutes.

See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html




回答2:


You have used mm which means minutes. Use capital MM instead.

You can find all date and time pattern symbols on the SimpleDateFormat Javadoc page.




回答3:


You need to use capital MM and not mm. Lower case 'mm' is for minutes and not for months.

So, your code would be :

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");



回答4:


Month is retrieved by MM, not mm.

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Refer to SimpleDateFormat JavaDoc:

M Month in year




回答5:


DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String dt = dateFormat.format(cal.getTime());

Use MM instead of mm.



来源:https://stackoverflow.com/questions/16424667/java-formatting-date

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