将文本输入字符串中的日期转换为其他格式的javascript

时间:2013-01-11 17:40:36

标签: javascript

我输入的日期是例如

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>

我是否应该这样做以获得一个警告框说“1月”?

3 个答案:

答案 0 :(得分:2)

试试这个新版本的行:

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

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

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

答案 1 :(得分: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的创建者

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