-4

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

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)

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

4

2 回答 2

4

ddd无法匹配SUNEEE如果您想匹配一周中的日期名称,请改用。

于 2013-05-21T10:22:25.197 回答
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();
}
于 2013-05-21T11:55:15.837 回答