java Cannot format given Object as a Date

、例子:

String MonthYear = null;    
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm/yyyy");    
String dateformat = "2012-11-17T00:00:00.000-05:00"
MonthYear = simpleDateFormat.format(dateformat);    
System.out.println(MonthYear);
2、解决方法:(这个错误的原因就是说,String类型无法直接parse为一个date类型,所以需要先把String字符串,格式化为一个datea类型,最后再格式化为你想要的格式)

DateFormat outputFormat = new SimpleDateFormat("yyyy/MM");
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = null;
        String inputText = "2012-11-17";
        try {
            date = inputFormat.parse(inputText);
        }catch (Exception e){
            e.printStackTrace();
        }
        String outputText = outputFormat.format(date);

————————————————
版权声明:本文为CSDN博主「渣男65」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/S_body/java/article/details/80453023

  

posted @ 2020-07-28 10:22  guguanghu  阅读(780)  评论(0编辑  收藏  举报