从文本区域获取值并正确存储它们

Getting values from a textarea and storing them correctly

本文关键字:存储 文本 区域 获取      更新时间:2023-09-26

我正在编写一个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日,它将不起作用,我不知道为什么。谁能发现我的错误?我已经搞砸了几个小时,但无济于事。有没有更简单的方法可以做到这一点?有什么方法可以只用一些正则表达式来做到这一点吗?我觉得我正在使这条路变得比我需要的更难。谢谢。

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

我猜是否有一个月的比赛,你会想要打破 for 循环。

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

首先将代码拆分为多个函数。然后将它们合并以擦除重复的代码。

  1. 功能检测格式
  2. 函数传输斜杠格式
  3. 函数传输空间格式
  4. 函数传输逗号格式

使每个功能都正常工作。然后联合2-4功能,擦除重复的代码。

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

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

它将返回一个日期对象,然后您可以根据需要对其进行操作,它适用于您给出的所有示例。