簡體   English   中英

使用Javascript,如何確保日期范圍有效?

[英]Using Javascript, how do I make sure a date range is valid?

在JavaScript中,確定提供的日期是否在有效范圍內的最佳方法是什么?

這方面的一個示例可能是檢查用戶輸入requestedDate是否是下一個有效工作周的一部分。 請注意,這不僅僅是檢查一個日期是否大於另一個日期,因為有效日期等於或大於范圍的下限,同時小於或等於范圍的上限。

這實際上是我在工作中看到的一個問題,以下代碼是我對問題的回答。

// checkDateRange - Checks to ensure that the values entered are dates and 
//     are of a valid range. By this, the dates must be no more than the 
//     built-in number of days appart.
function checkDateRange(start, end) {
   // Parse the entries
   var startDate = Date.parse(start);
   var endDate = Date.parse(end);
   // Make sure they are valid
    if (isNaN(startDate)) {
      alert("The start date provided is not valid, please enter a valid date.");
      return false;
   }
   if (isNaN(endDate)) {
       alert("The end date provided is not valid, please enter a valid date.");
       return false;
   }
   // Check the date range, 86400000 is the number of milliseconds in one day
   var difference = (endDate - startDate) / (86400000 * 7);
   if (difference < 0) {
       alert("The start date must come before the end date.");
       return false;
   }
   if (difference <= 1) {
       alert("The range must be at least seven days apart.");
       return false;
    }
   return true;
}

現在關於這段代碼需要注意Date.parseDate.parse函數應該適用於大多數輸入類型,但是已經知道某些格式的問題,例如“YYYY MM DD”,所以你應該在使用之前測試它。 但是,我似乎記得大多數瀏覽器會根據計算機區域設置解釋Date.parse的日期字符串。

此外,86400000的乘數應該是您要查找的天數。 因此,如果您正在尋找相隔至少一周的日期,那么它應該是七天。

因此,如果我理解當前,您需要查看一個日期是否比另一個更大。

function ValidRange(date1,date2)
{
   return date2.getTime() > date1.getTime();
}

然后,您需要使用Date.parse解析從UI獲取的字符串,如下所示:

ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));

這有幫助嗎?

var myDate = new Date(2008, 9, 16);

// is myDate between Sept 1 and Sept 30?

var startDate = new Date(2008, 9, 1);
var endDate = new Date(2008, 9, 30);

if (startDate < myDate && myDate < endDate) {
    alert('yes');
    // myDate is between startDate and endDate
}

您可以將各種格式傳遞給Date()構造函數來構造日期。 您還可以使用當前時間構建新日期:

var now = new Date();

並在其上設置各種屬性:

now.setYear(...);
now.setMonth(...);
// etc

有關詳細信息,請參閱http://www.javascriptkit.com/jsref/date.shtmlGoogle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM