1

I have a String like "2013-4-25" I need to convert this into "MM-dd-yyyy" format. Later I will have to append this date like

Calendar cal=new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);

How could I do this?

4

4 回答 4

2

使用SimpleDateFormat

        Date date = new Date();
        Calendar cal=new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.HOUR, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);

        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
        System.out.println(sdf.format(cal.getTime()));
于 2013-04-18T06:01:19.137 回答
2

用这个

String str = "2013-4-25";
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
        try {
            SimpleDateFormat parseFormatter = new SimpleDateFormat("yyyy-MM-dd");

            Date date = parseFormatter.parse(str);

            String formattedDate = formatter.format(date);
            System.out.println(formattedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
于 2013-04-18T06:06:43.540 回答
0

使用JodaTimeDateMidnight类,您不必自己规范日期。像这样的东西:

DateTimeFormatter format = DateTimeFormatter.fromPattern("yyyy-MM-dd");
DateMidnight date = DateMidnight.parse(date, format);

JDK 中的CalendarDateAPI 很痛苦……

于 2013-04-18T06:07:47.543 回答
0

您可以使用SimpleDateFormat. 检查此链接:http ://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

您可以指定您选择的格式化程序,然后相应地格式化日期。

于 2013-04-18T06:00:03.237 回答