Date Calculation using Js
I am using JS to calculate my date diffrence but i did not get the rounded value please guide me. Formula used to find the Approximate amount
value1 = todate - fromdate;
value2 = value1 / 30;
value3 = value2 * 5000;
for this i am using the following code
开发者_如何学C var preioddiff = parseInt(todate ) - parseInt(fromdate);
var dividen = preioddiff / 30;
var totappamt = dividen * parseInt(5000);
but it does not give the correct answer
for example From Date is 04012011 and to date is 04022011 if i subtract the value using the parseInt(todate ) - parseInt(fromdate); it return the value 13303380
instead of 0001000
Please explain your logic, Meena.
From what I see, your starting point is wrong.
You can't treat a date formatted as a string in the form "MMDDYYYY" and expect to be able to subtract them to do date calculations unless the two dates are in the same month. In that case, just deal with the days and ignore the year and month.
Your case: 04022011 - 04012011 == 0001000 (shouldn't that be 00010000 - note the extra zero at the end?)
What about: 04012011 - 03312011 - treating them as numbers, you'd get 00700000, but it should be that same as above since the two dates are only one day apart.
You might have to specify the base number, like this:
var res = parseInt('04022011', 10) - parseInt('04012011', 10);
It isn't very clear exactly what you're trying to do, but here's how you can get the number of days between two JavaScript Date objects:
var d1 = new Date('March 1');
var d2 = new Date('March 19');
var days_diff = Math.round((d2 - d1)/86400000);
alert(days_diff); // output is 18
When you subtract one Date from another, you get the number of milliseconds between them. Note that not all days have the same number of milliseconds (because of daylight savings) and obviously, months have different numbers of days, so doing date calculations this way has its risks.
If you are using parseInt
to parse a date string that may start with "0", ALWAYS put in a second argument to specify a radix (usually 10).
The string you passed to parseInt
will be interpreted as octal if it starts with a zero, which is what you have. You're never going to get correct results this way.
精彩评论