简体   繁体   English

如何在JavaScript中将日期差转换为数字

[英]how to convert date difference to number in javascript

I have designed a form which contains 3 fields From_date To_date No_of days i want to calculate the difference between from_date and to_date and the difference value will be shown in nu_of days. 我设计了一个表单,其中包含3个字段From_date To_date No_of days,我想计算from_date和to_date之间的差异,差异值将以nu_of days显示。 itried this code: 重复此代码:

<script>
function difference()
{
var d1=document.getElementById("P1_FROM_DATE");
var d2=document.getElementById("P1_TO_DATE");
var d3=document.getElementB`yId("P1_NO_DAYS");
if(d2.value < d1.value)
{
alert("todate should not be less than from date");
d2.focus();
return false;
}
else
{
d3.value=(d2.value - d1.value)+1;
return true;
}
}
</script>

when this code executes and the condition satisfies then the no_of_days shows me NaN. 当此代码执行且条件满足时,no_of_days会显示NaN。 So what is the solution please tell me. 那有什么解决办法请告诉我。

Regards Sabyasachi 问候Sabyasachi

You are trying to use date-based methods on fields that only know about text. 您试图在仅了解文本的字段上使用基于日期的方法。 You'll need to use the Date class to convert these values from text and use those methods to perform your date arithmetic. 您将需要使用Date类从文本转换这些值,并使用这些方法执行日期算术。

Good luck! 祝好运!

A generic formula. 通用公式。 The date[x]-format has to be ISO (eg 'yyyy/mm/dd'). date [x]格式必须为ISO(例如'yyyy / mm / dd')。

var diffDays = 
     Math.floor( (new Date([date1]) - new Date[date2]) / (1000*60*60*24) );

BTW, I suppose document.getElementById("P1_FROM_DATE") is an input field. 顺便说一句,我想document.getElementById("P1_FROM_DATE")是一个输入字段。 In that case use document.getElementById("P1_FROM_DATE").value to avoid disappointments. 在这种情况下,请使用document.getElementById("P1_FROM_DATE").value避免令人失望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM