Error Example:
Newnew Date (today.gettime () + 30* 1000*60*60*24);p rintln (today);p rintln (nextmonth);
Result:sat Sep 11:18:24 CST 2017
Sun Sep 18:15:37 CST 2017
Code Description: The purpose of the above code is to calculate the date after one months, from the results found to be obviously wrong (go back to the last month)
Cause analysis: 30* 1000*60*60*24, the expression, is intended to obtain a one-month millisecond count for calculation. However, Java defaults to using the int type to return the result type of the expression, which has exceeded the maximum range of the int type, so it becomes a negative number. result in incorrect calculation results.
The correct code (example one): In the expression, add the L-ID to the long type calculation
Date today = new Date ();D ate nextmonth = new Date (Today.gettime () + 30L * 1000*60*60*24);p rintln (today);p rintln (Nextmonth) ;
Result:sat Sep 11:22:06 CST 2017
Mon Oct 2017 11:22:06 CST
Correct code (example two): encapsulates the number of milliseconds in a day as a separate long constant, and is automatically treated as long when calculated
Date today = new Date (), Long one_day_milliseconds = 1000*60*60*24;date Nextmonth = new Date (Today.gettime () + * One_day _milliseconds);p rintln (today);p rintln (nextmonth);
Result:sat Sep 11:23:02 CST 2017
Mon Oct 2017 11:23:02 CST
Trample the pit sentiment:
The Java language does not have the ability to enter a long expression directly into an interpreted language, such as Python, when it comes to digital computing. As a numeric expression, because there is an int type limit, so beyond a certain range, be sure to display the type of l\d, otherwise it will be calculated error. If the parameter of the calculation is entered by the user himself, pay more attention to this problem (preferably into a string, and then use a larger data type to parse)
Java a pit record with the number of milliseconds to do date calculation