一尘不染

怎么把“ Mon Jun 18 00:00:00 IST 2012”转换成18/06/2012?

java

我有一个像下面的值Mon Jun 18 00:00:00 IST 2012,我想将其转换为18/06/2012

如何转换呢?

我尝试过这种方法

public String toDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date theDate = null;
        //String in = date + "/" + month + "/" + year;
        try {
            theDate = dateFormat.parse(date.toString());
            System.out.println("Date parsed = " + dateFormat.format(theDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateFormat.format(theDate);
    }

但它引发以下异常:

java.text.ParseException: Unparseable date: "Mon Jun 18 00:00:00 IST 2012"


阅读 318

收藏
2020-09-08

共1个答案

一尘不染

我希望以下程序可以解决您的问题

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
2020-09-08