字符串(“2013-4-25”)到目前为止的转换

时间:2013-04-18 05:57:16

标签: java string date format

我有一个类似的字符串 "2013-4-25" 我需要将其转换为"MM-dd-yyyy"格式。之后我将不得不追加date这样的

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

我怎么能这样做?

4 个答案:

答案 0 :(得分: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()));

答案 1 :(得分: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();
        }

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

使用JodaTimeDateMidnight课程,您无需自行规范化日期。像这样:

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

JDK中的CalendarDate API很痛苦......