2013-05-21 166 views
-4

我有一个日期格式,如“SA25MAY”;我需要将它转换为日期时间变量,然后我想在其中添加一天。然后我需要以相同的格式返回答案。请做一些要紧的Java:日期时间转换

try { 
    String str_date = "SA25MAY"; 
    DateFormat formatter; 
    Date date; 
    formatter = new SimpleDateFormat("ddd-dd-MMM"); 
    date = (Date) formatter.parse(str_date); 
    System.out.println("Today is " + date); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

错误:

java.text.ParseException: Unparseable date: "SA25MAY" 
at java.text.DateFormat.parse(DateFormat.java:337) 
at javadatatable.JavaDataTable.main(JavaDataTable.java:29) 

在这里,我不知道如何解决这个问题。

+3

['SimpleDateFormat'](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)是你正在寻找的。 – sp00m

+0

我收到像“SA25MAY”(Saturday25MAY)这样的输入,我不知道如何将它转换为日期时间变量 –

+1

请提供刚刚在您的问题中尝试的代码片段。 – sp00m

回答

1

如果因闰年(2月29日)而知道年份,则只能添加一天。

如果当年是当年,以下解决方案应该做的工作:

对于 “SA25MAY”:

try { 
    String str_date = "SA25MAY"; 

    // remove SA 
    str_date = str_date.replaceFirst("..", ""); 

    // add current year 
    Calendar c = Calendar.getInstance(); 
    str_date = c.get(Calendar.YEAR) + str_date; 

    // parse date 
    Date date; 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyddMMM"); 
    date = formatter.parse(str_date); 
    System.out.println("Today is " + date); 

    // add day 
    c.setTime(date); 
    c.add(Calendar.DATE, 1); 

    // rebuild the old pattern with the new date 
    SimpleDateFormat formatter2 = new SimpleDateFormat("EEEddMMM"); 
    String tomorrow = formatter2.format(c.getTime()); 
    tomorrow = tomorrow.toUpperCase(); 
    tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3); 
    System.out.println("Tomorrow is " + tomorrow); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

或为 “SA-25-MAY”:

try { 
    String str_date = "SA-25-MAY"; 

    // remove SA 
    str_date = str_date.replaceFirst("..-", ""); 

    // add current year 
    Calendar c = Calendar.getInstance(); 
    str_date = c.get(Calendar.YEAR) + "-" + str_date; 

    // parse date 
    Date date; 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MMM"); 
    date = formatter.parse(str_date); 
    System.out.println("Today is " + date); 

    // add day 
    c.setTime(date); 
    c.add(Calendar.DATE, 1); 

    // rebuild the old pattern with the new date 
    SimpleDateFormat formatter2 = new SimpleDateFormat("EEE-dd-MMM"); 
    String tomorrow = formatter2.format(c.getTime()); 
    tomorrow = tomorrow.toUpperCase(); 
    tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3); 
    System.out.println("Tomorrow is " + tomorrow); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

非常感谢...它的工作正常! –

4

ddd不能匹配SUN。如果您想在一周内匹配星期几名称,请改用EEE

+0

谢谢工作正常。但是在这里,我需要给出星期日的SUN,星期一的MON等等。但是我得到了像星期六一样的输入。它是一个两个字母。我试图匹配SU到EE,抛出错误 –