将字符串格式转换为其他日期格式

时间:2012-04-10 12:21:22

标签: blackberry java-me time

我的字符串格式为:M / d / yyyy h:m:s aa

现在,我想以yyyy-MM-ddTHH:mm:ss格式更改它。

如何以此格式更改它。请告诉我适当的解决方案

2 个答案:

答案 0 :(得分:4)

方法getConvertedDate(String)将进行纯文本解析以进行转换。

private String getConvertedDate(String inputDate) {
    // extract and adjust Month
    int index = inputDate.indexOf('/');
    String month = inputDate.substring(0, index);
    if (month.length() < 2) {
        month = "0" + month;
    }

    // extract and adjust Day
    inputDate = inputDate.substring(index + 1);
    index = inputDate.indexOf('/');
    String day = inputDate.substring(0, index);
    if (day.length() < 2) {
        day = "0" + day;
    }

    // extract Year
    inputDate = inputDate.substring(index + 1);
    index = inputDate.indexOf(' ');
    String year = inputDate.substring(0, index);

    // extract Hour
    inputDate = inputDate.substring(index + 1);
    index = inputDate.indexOf(':');
    String hour = inputDate.substring(0, index);

    // extract and adjust Minute
    inputDate = inputDate.substring(index + 1);
    index = inputDate.indexOf(':');
    String minute = inputDate.substring(0, index);
    if (minute.length() < 2) {
        minute = "0" + minute;
    }

    // extract and adjust Second
    inputDate = inputDate.substring(index + 1);
    index = inputDate.indexOf(' ');
    String second = inputDate.substring(0, index);
    if (second.length() < 2) {
        second = "0" + second;
    }

    // extract AM/PM marker
    // adjust hour, +12 for PM
    inputDate = inputDate.substring(index + 1);         
    String am_pm_marker = inputDate.substring(0);
    if (am_pm_marker.equalsIgnoreCase("pm")) {
        int hourValue = 0;
        try {
            hourValue = Integer.parseInt(hour);
        } catch (Exception e) {
        }
        hourValue += 12;
        hour = "" + hourValue;
        if (hour.length() < 2) {
            hour = "0" + hour;
        }
    } else {
        if (hour.length() < 2) {
            hour = "0" + hour;
        }
    }

    String outputDate = year + "-" + month + "-" + day;
    outputDate += "T" + hour + ":" + minute + ":" + second;
    return outputDate;
}

示例输入和输出:

String input = "04/01/2012 9:55:47 pm"; 
System.out.println("Output: " + getConvertedDate(input));
// Output: 2012-04-01T21:55:47

答案 1 :(得分:-2)

Date date = (Date)new SimpleDateFormat("M/d/yyyy h:m:s aa").parse(your_string_date);
String finalFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss").format(date)

基本上,第一个SimpleDateFormat识别您的原始格式并将其解析为Date。然后第二个将日期对象格式化为您需要的。

我没有jdk来测试这里,但它应该工作。

如果某些内容不起作用,请检查此链接的格式语法:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html