問題描述
如果您可以想象的話,這會在我的軟件中造成 Y2K 式的錯誤.奇怪的是一年的計算只發生在一年中的兩天,我不太確定如何排除故障.
This caused a Y2K-style bug in my software if you can imagine. Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.
輸出:
03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012
我不確定 Java 日期實用程序的哪一部分會導致此類錯誤.
I am not sure which part of the Java date utilities could cause such an error.
代碼(由于測試太小,我包含了一個完整的工作程序):
The code (since the test is so small I included a complete working program):
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateT {
private static String getFormattedBackscanStartTime(int days) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
Calendar workingDate = Calendar.getInstance();
workingDate.add(Calendar.DATE, -1 * days);
String formattedStartTime = dateFormat.format(workingDate.getTime());
return formattedStartTime;
}
public static void main(String args[]) {
for(int i = 35; i < 45; i++) {
System.out.println(getFormattedBackscanStartTime(i));
}
}
}
推薦答案
這是問題所在:
"dd-MMM-YYYY"
YYYY
是周年,而不是日歷年.你想要 yyyy
代替.
YYYY
is the week-year, not the calendar year. You want yyyy
instead.
2012 年的最后兩天在 2013 年的第一周.您通常應該只將周年與一年中的周"說明符 (w
) 結合使用.
The last two days of calendar year 2012 were in the first week of week-year 2013. You should normally only use the week year in conjunction with the "week of year" specifier (w
).
這篇關于Java 日期年計算按年關閉兩天的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!