我有日期字段,Onclick日期字段,我必須計算日期與當前日期。如果輸入日期比今天date.I必須彈出消息說日期是olderthan 1個月。Javascript日期計算
日期格式爲「yyyy-MM-dd」。我想與日期「1984-03-20」比較,以今天日期「2011-04-14」。它應返回月數。
對此的任何提示。 問候,
Chaitu
我有日期字段,Onclick日期字段,我必須計算日期與當前日期。如果輸入日期比今天date.I必須彈出消息說日期是olderthan 1個月。Javascript日期計算
日期格式爲「yyyy-MM-dd」。我想與日期「1984-03-20」比較,以今天日期「2011-04-14」。它應返回月數。
對此的任何提示。 問候,
Chaitu
看到這個discussion它有讓在JavaScript中的時間差演示。 這也是一個很好的例子:javascript-date-difference-calculation它顯示瞭如何在月,周或年中獲得差異。
@ user569125:你可以讓它接受yyyy-MM-dd格式的日期。 – 2011-04-15 04:37:21
也許這可以幫助你:
http://www.ozzu.com/programming-forum/javascript-date-comparison-t46552.html
<script language="JavaScript">
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2005");
today = new Date();
difference = Christmas - today;
days = Math.round(difference/(1000*60*60*24));
</script>
這不考慮夏令時。 – tcurdt 2013-11-08 16:51:52
最簡單的方法在JavaScript中比較日期是將其轉換爲一個日期對象,然後比較這些日期的對象。
下面你可以看到一個物體下面的功能:
dates.inRange (d,start,end)
Returns a boolean or NaN:
* true if d is between the start and end (inclusive)
* false if d is before start or after end.
* NaN if one or more of the dates are illegal.
var dt = new Date('02 Jul 2009');
dt.setMonth(dt.getMonth() – 1);
您可以閱讀上漲約JS Date對象,看看有什麼格式它都可以接受。
你可以做這樣的事情:
<script type="text/javascript">
function checkdate(){
var today = new Date()
var dating = document.getElementById("date").attr("value");
var new = new Date(dating);
var diff = today - new;
var days = Math.round(diff/(1000*60*60*24));
if (days >= 30){
alert("more than one month!");
}
}
</script>
<html><body>
<input type="text" id="date" onClick="checkdate();"/>
</html></body>
這會工作。將該字段的值傳遞給dateString onclick,並且代碼將確定日期是否大於1個月。
var dateString = '3/26/2011';
var selectDate = new Date(dateString); // convert string to date
var monthOld = new Date();
monthOld.setDate(monthOld.getDate() - 30); // subtract 30 days
if (selectDate < monthOld) {
alert('older than one month');
}
else alert('ok');
首先,我會建議你調整你的要求爲30天。這對你的用戶來說可能很好,對你和他們都是毫不含糊的。根據一年中的時間,1個月可以有不同的長度。
的解決方案開始
var millisecond = 1;
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var week = day* 7;
然後在日期輸入,如果你真的想這樣做基於間隔一個月再去做
var now = new Date();
if (usersDate < now.setMonth(now.getMonth() - 1))) {
//Do popup/whatever
}
你有一個這樣做
或者enterade日期的日期對象或只是全部字符串? – Felipe 2011-04-14 13:32:50
Felipe:我將以yyyy-MM-dd格式輸入字符串的日期。 – user569125 2011-04-14 14:51:46
然後,你可以做「新日期(theDateString)」有一個日期對象。關於如何使用下面的日期對象有很多答案。 – Felipe 2011-04-14 14:59:08