2011-04-26 331 views
1

我需要驗證不同日期的一些JavaScript(jQuery)。比較日期javascript

我有一個文本框,來自jquery的輸入掩碼(http://plugins.jquery.com/plugin-tags/inputmask)。我使用的面具是「d/m/y」。

現在我已經設置了一個CustomValidator函數來驗證日期。

我需要2個功能。一個檢查給定日期是否大於18年前。你必須年滿18歲。 檢查日期是否未來的功能之一。它只能在過去。

功能就像

function OlderThen18(source, args) { 
} 

function DateInThePast(source, args) { 
} 

你知道你回來與args.Value值27/12/1987

但是我怎樣才能檢查這個日期的功能?所以我可以將args.IsValid設置爲True或False。

我試圖分析字符串(27/12/1987),我從掩蓋的文本框回到日期,但我總是得到一個值,如27/12/1988。 那麼我怎麼能檢查與其他日期的給定日期?

+0

是否有一個原因,你沒有使用某種日期選擇器插件? – NT3RP 2011-04-27 00:59:08

回答

1

簡單的方式是18年加入到所提供的日期,看看結果是今天或更早的版本,例如:

// Input date as d/m/y or date object 
// Return true/false if d is 18 years or more ago 
function isOver18(d) { 
    var t; 
    var now = new Date(); 
    // Set hours, mins, secs to zero 
    now.setHours(0,0,0); 

    // Deal with string input 
    if (typeof d == 'string') { 
    t = d.split('/'); 
    d = new Date(t[2] + '/' + t[1] + '/' + t[0]); 
    } 

    // Add 18 years to date, check if on or before today 
    if (d.setYear && d.getFullYear) { 
    d.setYear(d.getFullYear() + 18); 
    } 
    return d <= now; 
} 

// For 27/4/2011 
isOver18('27/4/2011'); // true 
isOver18('26/4/2011'); // true 
isOver18('28/4/2011'); // false 
+0

謝謝,這是一個完美的解決方案。 – Sven 2011-04-27 07:10:42

1

試試這個啓動:

var d = new Date(myDate); 
var now = new Date(); 
if ((now.getFullYear() - d.getFullYear()) < 18) { 
    //do stuff 
} 
+0

除非處理瀏覽器的怪癖,否則不要使用getYear()。使用'getFullYear()'。此外,僅僅減去年份就不能準確地確定某人是否18歲,例如,在1993/12/31出生的人還沒有18,但2011 - 1993 = 18。 – RobG 2011-04-27 00:44:10

+0

@rob - 我同意'getFullYear()',但我只是提出了OP的一般解決方案。我相信他可以自己找出數學問題:) – Jason 2011-04-27 00:56:10

0

javascript日期對象是相當靈活,可以處理許多日期字符串。 您可以比較兩個Date對象或使用日期接口方法(例如getSeconds(),getFullYear())以推導出有關日期的有用數據。

請參閱Date object reference formore details。

0

你需要建立,修改和比較Date objects - 這樣的事情:

// str should already be in dd/mm/yyyy format 
function parseDate(str) { 
    var a = str.split('/'); 
    return new Date(parseInt(a[2], 10), // year 
        parseInt(a[1], 10) - 1, // month, should be 0-11 
        parseInt(a[0], 10)); // day 
} 

// returns a date object for today (at midnight) 
function today() { 
    var date = new Date(); 
    date.setHours(0, 0, 0); 
    return date; 
} 

function DateInThePast(str) { 
    // date objects can be compared like numbers 
    // for equality (==) you'll need to compare the value of date.getTime() 
    return parseDate(str) < today(); 
} 

function OlderThan18(str) { 
    // left as an exercise for the reader :-) 
}