Java a pit record with the number of milliseconds to do date calculation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.