2013-05-12 4 views
1

나는 회사 부동산 중개업기구에서 일하기 때문에 직원을위한 내부 페이지를 만들고 있는데, 사용하기위한 몇 가지 작은 도구가 포함되어 있습니다. 다른 것들 사이.Javascript : 임차인의 잔여 시간 계산 (렌트 계산기)

내가 집어 넣으려고했던 것 중 하나는 렌탈 금액과 임대 기간이 사용자에게 주어지면 임대 시간과 (그리고 오늘부터) 임대 시간을 결정해야한다는 것입니다. 임대료가 얼마 남았는지 조언하십시오.

I했습니다는 주로 작업하지만, 당신이 상당히 길어 볼 수있다 (나는 그것이이어야 어느 정도 있으리라 믿고있어) 나는 합리적으로 지저분한 느낌을 가지고 다음의

//calculates the remaining rent left to pay for terminated leases 
$("input[name='calcRent']").click(function() { 
    //gets rent and daily rent for later calculations 
    var rent = $("input[name='rentRent']").val(); 
    var dailyRate = (rent * 12)/365; 
    var leaseExpiry = $("input[name='leaseExpiry']").val(); 
    var remRent = $("input[name='remRent']"); 
    //breaks down lease expiry date and today's date into day, month, year parts 
    //so that units can be used in calculations 
    var ldd = leaseExpiry.substr(0,2); 
     ldd = parseInt(ldd, 10); 
    var lmm = leaseExpiry.substr(3,2); 
     lmm = parseInt(lmm, 10); 
    var lyyyy = leaseExpiry.substr(6,4); 
     lyyyy = parseInt(lyyyy, 10); 
    var date = new Date(); 
    var tdd = date.getDate(); 
    var tmm = date.getMonth()+1; 
    var tyyyy = date.getFullYear(); 
     //if the expiry month is next year (or later) add 12 to expiry 
     //month value to make "lmm - tmm" calculation give positive value 
     if (lyyyy > tyyyy) { 
      lmm += (12 * (lyyyy - tyyyy)); 
     } 
    //takes the current month from the expiry month to get the number of 
    //whole months left in the lease, then checks day values to see whether 
    //we have already passed the rent due date for this month (and so there's 
    //one less whole month left than we originally thought), taking 1 from 
    //wholeMths value if so 
    var wholeMths = lmm - tmm; 
     if (ldd == (tdd - 1)) { 
      wholeMths = wholeMths; 
     } else if (ldd < (tdd - 1)) { 
      wholeMths -= 1; 
     } 
    //works out if there are any days to be charged at daily rate (i.e. not 
    //part of a whole month). If today's date(tdd) == expiry date(ldd)+1 we have no 
    //leftover days (rental month runs like so: 12/04 - 11/05). If tdd > ldd+1 
    //(leftover days cross over a month end) we set checkMonth to true so the following 
    //if statement runs 
    var checkMonth = false; 
    var daysLeft = 0; 
     if (tdd == (ldd + 1)) { 
      daysLeft = 0; 
     } else if (tdd > ldd + 1) { 
      daysLeft = (31 - tdd) + ldd; 
      checkMonth = true; 
     } else { 
      daysLeft = ldd - tdd; 
     } 
     //as per the above line: "daysLeft = (31 - tdd) + ldd;" we assume months have 31 days 
     //as the majority do, this if checks whether the month end that we cross over with our 
     //leftover days actually has 30 days, if not we check whether it's February and whether 
     //it's a leap year so that we get the appropriate no. of days to charge for - if it meets 
     //any of these criteria the relevant no. of days are subtracted from daysLeft 
     if ((lmm == 05 || lmm == 07 || lmm == 10 || lmm == 12 
      || lmm == 17 || lmm == 19 || lmm == 22 || lmm == 24) && checkMonth) { 
      daysLeft -= 1; 
     } else if ((lmm == 03 || lmm == 15) && checkMonth) { 
      if (lyyyy % 4 == 0) { 
       daysLeft -= 2; 
      } else { 
       daysLeft -= 3; 
      } 
     } 
     checkMonth = false; 
    var balance = (wholeMths * rent) + (daysLeft * dailyRate); 

    remRent.val(balance.toFixed(2));   
}); 

하나 특히 나를 괴롭히는 것은 임대 만기가 다음 해에 발생하는 부분입니다. 나는 그 달의 '가치'를 정당하게 다루는 방법에 대해 머리를 숙이지 않았다 (당신이 마지막에서 볼 수 있듯이).

의견에 대한 숫자와 볼륨이 실제 코드와 약간 불균형을 보였으므로이 점에 대한 제안은 만족 스러울 것입니다. 그러나 그 일이 너무도 명확하지 않아 현재로서는 필요하다고 생각합니다.

감사합니다,

작업을 완료,하지만 당신이 활용할 필요가 무엇인지에
+0

[moment.js] (http://momentjs.com/)가 도움이 될 수 있습니다. – JAM

+3

이것에 대해 XY 문제가 있습니다. 나는 당신의 코드를보고, 당신이 달성하고자하는 것을 어느 정도는 보지만, 실제로 질문을하지 않았고, 원래의 '스펙 계산'이 아닌 최종 코드만을 볼 수 있기 때문에, 좋은 코드를 만들 었는지 여부를 결정하십시오. –

+0

moment.js는 크기를 약간 줄이면 편리 할 것 같습니다. 감사합니다. Niels - 코드 외부에서 제공되는 유일한 데이터는 월 임대료이며 임차가 끝나는 날짜입니다. 출력은 단순히 숫자입니다 (오늘부터 위에 언급 된 임대료 금액 날짜). 나는 데이터에 아무런 문제가 없다. 그리고 그것은 균형을 출력하고있다. 그러나 위와 같이 나의 임대료 만기 날짜가 우리가 현재의 것일 때인 지저분한 일이라면 내 관심사는 결승전 주변이다. 그리고 그 모든 것을 파악하는 더 좋은 방법이 있는지? – Josh

답변

1

좋은 일에 내장 된 Date 클래스를 사용하여 자바 스크립트에서 사용할 수있는 날짜 계산. 특히

사이 다음과 같은 논리를 사용할 수 날짜에 일 수를 얻을 수 있습니다 :

var currentDate = new Date(); // This will get today's date 
currentDate.setHours(0,0,0,0); // Remove time from consideration 
           // As recommended by @NickSlash 

// The following get's the lease expiration date using the year, 
// month and date that you have already extracted from the input 
var leaseExpirationDate = new Date(lyyyy, lmm, ldd); 

// The number of days remaining in the lease is simply the following: 
var one_day = 1000*60*60*24; 
var daysLeftInLease = (leaseExpirationDate - currentDate)/one_day; 

내부적으로 Date 클래스는 1970 년 1 월 1 일 이후 번호 밀리 초 단위로 날짜 값을 유지하기 때문에이 마법 발생 . 따라서 두 개의 Date 개체를 뺀 경우 두 개체 사이의 밀리 초 수가됩니다. 그런 다음 해당 날짜를 하루 중 밀리 초 수로 나누면 날짜 사이의 일 수를 구할 수 있습니다.

+0

원본 코드에서 복잡한 계산의 많은 부분은 실제로 ** 유닉스 타임 스탬프 기반 계산을 원하지 않음 **에서 비롯된 것입니다. 일반적으로 임대료는 월 단위로 지불되므로 많은 윤리적 계산에는 1 월 15 일과 3 월 15 일이 윤년에 따라 59 일 또는 60 일이 아닌 "2 개월 간격"임을 알 필요가 있습니다. –

+1

함수는 (남은 임대료) 하나의 결과를 반환 (또는 설정)합니다. 계산 결과와 무관한데, 같은 대답을 제안하려고합니다. D : currentDate.setHours (0,0,0,0); 또는 현재 시간이 결과에 영향을 미치지 않도록 숫자를 반올림합니다. – NickSlash

+0

Niels는 옳다고 생각합니다. 임대료가 매월 청구되기 때문입니다 (어느 것이!= 일일 요금, 그렇지 않은 경우 월별 임대료는 모든 12 개월 동안 동일하지 않을 것입니다 - 전체 월이 아닐 때 일일 요금에만 적용됩니다.) 이렇게 계산하면 잘못된 수치가 표시됩니다. 그것을 시도 : 임대료 = 100; 리스 만기 = 2014 년 11 월 3 일; 그리고 나는 그것이 둥근 1000 이었음에 틀림없는 1094.89를 얻었다. 그것은 코드를 많이 잘라 내기 때문에 성가신 것이다 :) – Josh