2016-05-04 147 views
0

這是我的時間差來計算日子的代碼和我的yy-dd-mm用戶的日期格式,但我已經改變了我的格式dd-mm-yy。所以我已經改變了格式代碼,但它不能正常工作。 請任何人都可以在這方面幫助?更改日期甲

<script> 
var calculate = function() { 
    var from = document.getElementById("txtdate").value; 
    var fromdate = from.slice(3, 5); 
    fromdate = parseInt(fromdate); 
    var frommonth = from.slice(0, 2); 
    frommonth = parseInt(frommonth); 
    var fromyear = from.slice(6, 10); 
    fromyear = parseInt(fromyear); 
    var to = document.getElementById("txtdate1").value; 
    var todate = to.slice(3, 5); 
    todate = parseInt(todate); 
    var tomonth = to.slice(0, 2); 
    tomonth = parseInt(tomonth); 
    var toyear = to.slice(6, 10); 
    toyear = parseInt(toyear); 
    var oneDay = 24*60*60*1000; 
    var firstDate = new Date(fromyear,frommonth,fromdate); 
    var secondDate = new Date(toyear,tomonth,todate); 

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay))+1); 
    if (diffDays) 
     document.getElementById("result").value=diffDays; 

} 
</script> 
+0

Checkout moment.js庫,它真的很棒,並會幫助你添加/減少/創建差異:) – PolishDeveloper

回答

1

您應該使用from.split(' - ')函數來獲取日期,月份,年份。然後,從和創建兩個新的日期(年,月,日)。 newTo-newFrom以2毫秒爲單位給出日期差異。除以1000 * 3600 * 24這種差異來獲得天的時間差

var diffDays = Math.ceil(timeDiff/(1000 * 3600 * 24)); 

參考文獻見Get difference between 2 dates in javascript?

0
<html> 
<head> 
    <title></title>  
</head> 
<body> 
<input type="text" id="txtdate" value="16-04-2016" /> 
<input type="text" id="txtdate1" value="24-05-2016" /> 

<input type="text" id="result" value="" /> 

<!-- dd-mm-yyyy --> 
<script type="text/javascript"> 
var calculate = function() { 
    var from = document.getElementById("txtdate").value; 
    var to = document.getElementById("txtdate1").value;   
    document.getElementById("result").value= process(to,from)+' Days'; 
} 

function process(d1,d2){ 
var date1 = d1.split('-'); 
var date2 = d2.split('-'); 
var start = new Date(date1[2], +date1[1]-1, date1[0]); 
var end = new Date(date2[2], +date2[1]-1, date2[0]); 
return (start.getTime() - end.getTime())/(1000*60*60*24); 
} 

calculate(); 

</script> 
</body> 
</html> 

Fiddle

2

搜索ñ替換代碼的這兩行:

var fromdate = from.slice(3, 5); 
var frommonth = from.slice(0, 2); 

TO:

var fromdate = from.slice(0, 2); 
var frommonth = from.slice(3, 5); 

搜索和替換thest兩行:

var todate = to.slice(3, 5); 
var tomonth = to.slice(0, 2); 

TO:

var todate = to.slice(0, 2); 
var tomonth = to.slice(3, 5); 

行的其餘假期,因爲它們是。