1

我输入的日期是例如

var startDate = "January 16, 2013"

从我试图深入研究的旧帖子中,我知道我可能需要使用http://www.javascripttoolbox.com/lib/date/documentation.php中的 date.js

所以我在我的 html 中有一个额外的行来启动它

<script src="http://prestigeswimming.com/wp-content/plugins/cred-frontend-editor/date.js" type="text/javascript"></script> 
<script type="text/javascript">
   var startDate = "January 16, 2013"
   alert(startDate.getMonthName());
</script>

我应该这样做以获得一个提示框,上面写着“一月”吗?

4

3 回答 3

2

试试这个新版本的行:

var startDate = Date.parseString( "January 16, 2013");

为了使用该库,您必须使用 Date() 对象。

parseString 是该对象上的一个函数,它返回一个 Date 对象。

于 2013-01-11T17:44:56.877 回答
0

如果您只处理美国语言环境日期并且需要将任意字符串输入解析为日期,您还可以查看Sherlock.js以将字符串解析为 Date 对象。然后,要获取月份名称,只需在 Javascript 中操作:

var Sherlocked = Sherlock.parse('January 16');
var month = Sherlocked.startDate.getMonth();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
alert(months[month]);

Sherlock.js 不会解析年份。如果您需要对此的支持,您可以使用 Sherlock 的预处理器系统自己解析这一年。

披露:我是 Sherlock.js 的创建者

于 2013-01-11T19:32:26.470 回答
-1

无需使用库:

var startDate = "January 16, 2013";
var d = new Date(startDate);
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();

alert(month + "-" + day + "-" + year);

http://jsfiddle.net/mPBSf/

以下会将您的日期格式转换为有效的 ECMAScript 日期格式:

var startDate = "ApRiL 16, 2013";
var noCommas = startDate.replace(/\,/g,'');
var withDashes = noCommas.replace(/ /g,"-");

function monthsToNumbers(date)
{
  var months = ["january","february","march","april","may","june","july","august","september","october","november","december"];
  var year;

  date = date.toLowerCase();

  for(var i = 0; i < months.length; i++)
  {
    if(date.indexOf(months[i]) != -1)
    {
      if(i+1 < 10)
        date = date.replace(months[i],"0" + (i+1));
      else
        date = date.replace(months[i],i+1);
    }
  }

  year = date.match(/\d{4}/);
  date = date.replace(year, "");
  date = year + "-" + date;
  date = date.substring(0,date.length-1);

  return date;
}

var d = new Date(monthsToNumbers(withDashes));
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();

alert(d);

http://jsfiddle.net/kWzSv/1/

于 2013-01-11T17:50:04.700 回答