如果因閏年(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();
}
['SimpleDateFormat'](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)是你正在尋找的。 – sp00m
我收到像「SA25MAY」(Saturday25MAY)這樣的輸入,我不知道如何將它轉換爲日期時間變量 –
請提供剛剛在您的問題中嘗試的代碼片段。 – sp00m