1

I am trying to convert date from one format to other format but the following code is giving me the exception: please help

public class Formatter {
        public static void main(String args[]) {

            String date = "12-10-2012";
            try {
                Date formattedDate = parseDate(date, "MM/dd/yyyy");
                System.out.println(formattedDate);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public static Date parseDate(String date, String format)
                throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat(format);
            return formatter.parse(date);
        }

    }
4

4 回答 4

11

要将“MM-dd-yyyy”转换为“MM/dd/yyyy”,您必须执行以下操作:

SimpleDateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
Date date = format1.parse("12-10-2012");
System.out.println(format2.format(date));

如果您输入"12-10-2012",则输出将是"12/10/2012"

于 2012-06-07T13:40:40.567 回答
6

change slash / to dash -

MM-dd-yyyy instead of MM/dd/yyyy

it should be Date formattedDate = parseDate(date, "MM-dd-yyyy");

于 2012-06-07T13:19:11.840 回答
5

您的格式使用斜杠 (/),但您提供的日期使用破折号 (-)。改成:

Date formattedDate = parseDate(date, "MM-dd-yyyy");

你应该很好:)

于 2012-06-07T13:19:51.247 回答
1

尝试这个。

Date formattedDate = parseDate(date, "MM-dd-yyyy");
于 2012-06-07T13:21:18.923 回答