从textarea获取值并正确存储

时间:2016-03-17 02:38:06

标签: javascript

我正在编写一个JavaScript程序来确定给定日期的星期几。用户在文本框中键入日期,然后按提交。

可以输入日期的方式是:

Day/Month/Year --> 6/15/95 for June 6th, 1995
                   6/15/1995 for the same date
Day Month Year --> 15 September 2006
Month Day Year --> February 19, 1994

我接受了Day/Month/YearMonth Day, Year,但出于某种原因,我无法接受它与当月的一天接受它。到目前为止,这是我的代码。

var monthArray = ["January", "February", "March",
                  "April", "May", "June", "July",
                  "August", "September", "October",
                  "November", "December"];

var month;
var day;
var year;

var text1 = getElementById("myTextArea").value;      
var text2 = text1.split(/[\s\/,]+/);  //15 Sep 2001 will be ["15", "Sep", "2001"]
                                      //6/13/95 will be ["6", "13", "95"]
                                      //Sep 15, 2001 will be ["Sep", "15", "2001"]

for(var i = 0; i < text2.length; i++)    //Iterate through all elements in text2
{
   for(var j = 0; j < monthArray.length; j++) //Iterate through all elements in monthArray
   {
      if(text2[i].substring(0, 3) == monthArray[j].substring(0, 3))   //See if one of the elements matches a month string.
      {
         month = j + 1;   //Set month equal to the number. For instance, if Sep month = 9
         text2.splice(i, i + 1);  //Remove the month element. Array should contain ["date", "year"] in that order
         day = text2[0];    //Set day equal to the "date" element.
         year = text2[1];   //Set year equal to the "year" element.
      }
   }
}

if(typeof month == "undefined")    //This will happen if month isn't a string. I.e. it is a number like 5/16/54.
{
   month = text2[0];
   day = text2[1];
   year = text2[2];
}

//This is for a specified year range.
if(year >= 50 && year < 100)
{
   year = 1900 + parseInt(year);
}
else if(year <= 49 && year >= 0)
{
   year = 2000 + parseInt(year);
}

当我输入类似于6/15/95或1995年6月15日的东西时,它可以正常工作。但出于某种原因,如果我试图进入1995年6月15日,它将无法工作,我不知道为什么。谁能发现我的错误?我一直在搞乱这几个小时但没有用。有更简单的方法吗?我只用一些正则表达式就可以做到这一点吗?我觉得我这样做比我需要的更难。感谢。

3 个答案:

答案 0 :(得分:0)

您的代码不清楚。 可读性更重要。

首先将代码拆分为多个函数。然后联合起来擦除重复的代码。

  1. function detectFormat
  2. function transferSlashFormat
  3. function transferSpaceFormat
  4. function transferCommaFormat
  5. 让每个功能都有效。 然后联合2-4函数,擦除重复的代码。

答案 1 :(得分:0)

text2.splice(i,i + 1);如果存在月匹配,则导致text2 [i]在下一循环迭代中变为未定义。然后,您尝试在undefined上调用substring,这会引发错误。

我猜测是否有月份匹配,你会想要摆脱for循环。

答案 2 :(得分:0)

您可以从这样的字符串中获取日期:

var string = "Sep 15, 2001";
var d = new Date(string)

它将返回一个Date对象,然后您可以根据需要操作它, 它适用于你提供的所有例子。