0

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

现在,我想将其更改为 yyyy-MM-ddTHH:mm:ss 格式。

我怎样才能以这种格式更改它。请告诉我适当的解决方案

4

2 回答 2

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
于 2012-04-11T10:11:34.293 回答
-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 识别您的原始格式并将其解析为日期。然后第二个将日期对象格式化为您需要的格式。

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

检查此链接的格式语法以防万一出现问题:
http ://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

于 2012-04-10T12:32:56.863 回答