substring javascript和html

时间:2013-05-13 09:18:30

标签: javascript html

<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 //&lt; - 这不起作用,因为第一个字母是“ - ”

我的文字输入只接受日期 2013年11月23日//&lt; ---将工作。

但是对于我的功能,如果我插入日期像-23-11-2013 它会显示无效的月份。我该怎么做我的功能改变

4 个答案:

答案 0 :(得分:0)

检查javascript子字符串函数here

我的示例:结果为est

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

答案 1 :(得分:0)

试试这个......

var date =“ - 23-11-2013”​​;

data = date.split(“ - ”);

if(data.length == 3){

如果(号码(数据[0])&GT; 31){

alert(“无效的日期格式”);

}否则if(Number(data [1])&gt; 12){

提醒(“月份格式无效”);

} }否则{

警告(“格式不正确”);

}

答案 2 :(得分:0)

他是一个你可以使用的更好的功能:

function myFunc(s) {

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

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

它应该返回无效日期日期对象。

myFunc("23-11-2013")myFunc("-23-11-2013")之类的通话应该返回日期对象

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

答案 3 :(得分: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