如何使用简单日期格式格式化日期而不是年份?

时间:2013-09-07 11:05:45

标签: java

有以下代码:

public static String getDateOnCurrentTimezone(String date, String timezone) {
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd kk:mm:ss"); 
    sdf.setTimeZone(TimeZone.getTimeZone(timezone));
    try {
        Date d = sdf.parse(date);
        sdf.setTimeZone(TimeZone.getDefault());
        return sdf.format(d);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

此代码必须将日期从一个时区格式化为另一个没有日期的时区,但始终返回“null”。如果我将格式更改为“yyyy-MM-dd”,则效果很好。我该如何解决?谢谢。

2 个答案:

答案 0 :(得分:1)

如果要解析日期并返回具有不同表示形式的String,则需要两个DateFormats:

Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
String result = new SimpleDateFormat("MM-dd kk:mm:ss").format(d);

请注意,您可能打算使用HH代替kk。检查javadoc,看看有什么区别。

答案 1 :(得分:0)

问题在你的参数中,你试图解析日期:

2013-09-05 19:48:05

格式为

MM-dd kk:mm:ss

这有两个问题:

  1. 小时,k代表1-24,您可能想要使用HH(0-23),请参阅Oracle Documentation
  2. 格式不一样,传递的格式为:yyyy-MM-dd HH:mm:ss
  3. 试试这段代码:

    public static String getDateOnCurrentTimezone(String date, String timezone) {
    
        SimpleDateFormat outPutParser = new SimpleDateFormat("MM-dd HH:mm:ss");
        SimpleDateFormat inputPutParser = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
    
        outPutParser.setTimeZone(TimeZone.getTimeZone(timezone));
        try {
    
            Date d = inputPutParser.parse(date);
            outPutParser.setTimeZone(TimeZone.getDefault());
            return outPutParser.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    

    抱歉我的英文不好