如何在SimpleDateFormat中制作2015-09-04T11:30:06-0500到2015-09-04T11:30:06-05:00的格式

时间:2015-10-26 17:36:06

标签: java

使用下面的代码,但没有得到确切的输出。

期望的输出:

2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00

实际输出:

dateValue => 2015-10-19T16:52:23-0400
a => 2015-10-20T02:22:23+0530

我的代码:

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String a = formattedDate("2015-10-19T16:52:23-0400");
        System.out.println  ("a => " + a);
    }

    public static String formattedDate (String dateValue) {
        String expectedFormat = "";
        SimpleDateFormat inputDateFormat =
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        SimpleDateFormat outputDateFormat =
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");

        try {
            System.out.println("dateValue => " + dateValue);
            if (dateValue == null || dateValue.isEmpty()) {
                dateValue = "";
            }
            inputDateFormat.setLenient(true);
            Date d = inputDateFormat.parse(dateValue);
            expectedFormat = outputDateFormat.format(d);
        } catch (Exception e) {
            // Sending back the current datetime in the desired format
            Calendar cal = Calendar.getInstance();
            expectedFormat = outputDateFormat.format(cal.getTime());
        }

         return expectedFormat;
    }
}

3 个答案:

答案 0 :(得分:2)

在Java 7及更高版本中,您可以使用XXX输出带有列的时区:

SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

当您使用它来格式化数据时,它将返回例如:

2001-07-04T12:08:56-07:00

有关更多示例,请参阅{{3}}。

答案 1 :(得分:1)

由于我使用的是1.6,因此不支持XXX。所以用替代方法来实现这一点。这就是我为替代方式所做的事情。



public static String formattedDate (String dateValue) {
        StringBuilder expectedFormat;
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        try {
            if (dateValue == null || dateValue.isEmpty()) {
                dateValue = "";
            }
            inputDateFormat.setLenient(false);
            Date d = inputDateFormat.parse(dateValue);
        } catch (Exception e) {
            System.out.println("Error in parsing : " + e.getMessage());
            // Sending back the current datetime in the desired format
            Calendar cal = Calendar.getInstance();
            dateValue = inputDateFormat.format(cal.getTime());          
        } finally {
            expectedFormat = new StringBuilder(dateValue).insert(dateValue.length()-2, ":");
        }       
        return expectedFormat.toString();       
    }

答案 2 :(得分:1)

当你只需要改变第三个最后一个字符时,给一个字符串作为参数如何留下一个字符串?

public static String formattedDate (String dateValue)
{
    return dateValue.substring(0, dateValue.length() - 2) 
            + ":"
            + dateValue.substring(dateValue.length() - 2);
}

Output:
a => 2015-10-19T16:52:23-04:00
相关问题