Improper result of SimpleDateFormat

本秂侑毒 提交于 2019-12-18 09:42:17

问题


I want to convert Tue Jun 01 00:00:00 IST 112 into 01-JUN-2012

I used

 Calendar calendar = new GregorianCalendar(year, 6, Calendar.DAY_OF_MONTH); 
     Date maxDate=new Date();
     maxDate=calendar.getTime();  
     calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 
      SimpleDateFormat s=new SimpleDateFormat("dd-mmm-yyyy");
       s.format(maxDate);

But I get 30-000-0112


回答1:


Use CAPITAL M for month,

 SimpleDateFormat s=new SimpleDateFormat("dd-MMM-yyyy");

Also you are setting date first and then you are resetting calendar which I guess not what you want to do so may be you need to change it to as follows

Date maxDate=new Date();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 
maxDate=calendar.getTime();  
SimpleDateFormat s=new SimpleDateFormat("dd-MMM-yyyy");
s.format(maxDate);

See

  • SimpleDateFormat API doc



回答2:


Use capital MMM in date format as shown below -

  SimpleDateFormat s=new SimpleDateFormat("dd-MMM-yyyy");

Everything else is ok

    Calendar calendar = Calendar.getInstance();
     Date maxDate=new Date();
     maxDate=calendar.getTime();  
     calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 
     SimpleDateFormat s=new SimpleDateFormat("dd-MMM-yyyy");
     System.out.println(s.format(maxDate));

output would be - 06-Jul-2012



来源:https://stackoverflow.com/questions/11356109/improper-result-of-simpledateformat

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