2013-05-13 58 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