2013-05-13 31 views
0
<script> 
function myFunction(){ 
//Example I passed in 31-02-2013 
//var timeDate = document.getElementById('date').text; <--This Wont Work! 
//This is some very basic example only. Badly formatted user entry will cause all 
//sorts of problems. 
var timeDate = document.getElementById('date').value; 

//Get First 2 Characters 
var first2 = timeDate.substring(0,2); 
console.log(first2); 

var dateArray = timeDate.split("-"); 
console.log(dateArray[0]); 

var date = parseInt(dateArray[0], 10) ;//Make sure you use the radix otherwise leading 0 will hurt 
console.log(date); 
if(date < 1 || date > 30) 
    alert("Invalid date"); 

var month2 = timeDate.substring(3,5); 
console.log(month2); 

var monthArray = timeDate.split("-"); 
console.log(monthArray[1]); 

var month = parseInt(monthArray[1],10); 
console.log(month); 

if(month < 1 || month > 12) 
    alert("Invalid month"); 
} 
</script> 

我的功能是否正常工作,只是我想一些修正一樣,如果用戶輸入 -23-11-2013 // < - 這將不作爲第一個字母的工作「 - 」子JavaScript和HTML

我的文本輸入只接受日期 23-11-2013 // < ---將工作。

但對於我的功能,如果我插入日期如-23-11-2013 它將顯示無效的月份。我應該做一些改變了我的功能

+0

您可以創建這個小提琴? – 2013-05-13 09:22:18

+0

你想要你的功能做什麼?只需在輸入字符串的開始處刪除一個可能的*連字符*? – MCL 2013-05-13 09:30:34

回答

0

檢查的JavaScript字符串函數here

我的例子:結果est

var a ="test"; 
console.log(a.substring(1)); 
0

嘗試......

VAR日期=「 - 23-11-2013" ;

數據= date.split( 「 - 」);

如果(data.length == 3){

如果(號碼(數據[0])> 31){

警報( 「無效的日期格式」);

}否則如果(號碼(數據[1])> 12){

警報( 「無效月格式」);

}} 其他{

警報( 「不正確的格式」);

}

0

他是一個更好的功能,你也許可以使用:

function myFunc(s) { 

    s = s.split("-").filter(Number); 

    return new Date(s[2], s[1], s[0]); 
} 

它要麼返回無效的日期Date對象。

所以像myFunc("23-11-2013")myFunc("-23-11-2013")調用應返回Date對象

Mon Dec 23 2013 00:00:00 GMT+0530 (India Standard Time) 
0

這裏是一個更好的功能,您可以使用:

function myFunction(date) { 
    var args = date.split(/[^0-9]+/), 
     i, l = args.length; 

    // Prepare args 
    for(i=0;i<l;i++) { 
    if(!args[i]) { 
     args.splice(i--,1); 
     l--; 
    } else { 
     args[i] = parseInt(args[i], 10); 
    } 
    } 

    // Check month 
    if(args[1] < 1 || args[1] > 12) { 
    throw new Error('Invalid month'); 
    } 
    // Check day (passing day 0 to Date constructor returns last day of previous month) 
    if(args[0] > new Date(args[2], args[1], 0).getDate()) { 
    throw new Error('Invalid date'); 
    } 

    return new Date(args[2], args[1]-1, args[0]); 
} 

注重當月在Date構造函數是基於0,你需要從實際值中減去1。除此之外,你有錯誤的日子檢查,因爲不同的月份有不同的天數。提供的功能還允許使用空格和特殊字符來傳遞-23 - 11/2013等值,唯一重要的是數字順序(日,月,年)。

在這裏你可以看到它的工作http://jsbin.com/umacal/3/edit