Java date annual calculation is closed two days a year
•
Java
If you can imagine, this will cause Y2K style errors in my software Strangely, the annual calculation only takes place on two days of the year. I'm not sure how to troubleshoot
Output:
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
I don't know which part of the Java date utility might cause such an error
Code (since the test is very small, I include 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)); } } }
Solution
This is the problem:
"dd-MMM-YYYY"
Yyyy is an anniversary, not a calendar year You want yyyy instead
The last two days of 2012 are in the first week of 2013 You can usually only use the annual and weekly specifiers (W)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码