最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is wrong with getMonth() + 1; - Stack Overflow

programmeradmin1浏览0评论

I have this code in Sharepoint:

     var d = $.trim(oListItem.get_item('Begindatum'));
     alert(d);
     var m = d.getMonth() + 1;
     alert(m);

The first alert returns: Thu Apr 20 2017 00:00:00 GMT+0200 (W. Europe Daylight Time), which is correct.

The second alert (m) is not fired and the code after that is not executed. What is wrong with my code?

I have this code in Sharepoint:

     var d = $.trim(oListItem.get_item('Begindatum'));
     alert(d);
     var m = d.getMonth() + 1;
     alert(m);

The first alert returns: Thu Apr 20 2017 00:00:00 GMT+0200 (W. Europe Daylight Time), which is correct.

The second alert (m) is not fired and the code after that is not executed. What is wrong with my code?

Share Improve this question asked Jun 2, 2017 at 9:25 johannesjohannes 1,4481 gold badge13 silver badges26 bronze badges 6
  • Look into the browser console if you see any error – Jens Commented Jun 2, 2017 at 9:27
  • 1 Your d is a string, not a Date object. – georg Commented Jun 2, 2017 at 9:27
  • 1 $.trim() returns a string – Andreas Commented Jun 2, 2017 at 9:27
  • 1 I guess d is a string not a date – Jens Commented Jun 2, 2017 at 9:28
  • If you trim something, then it is probably a string value, and not a Date object. Ergo, you can not call Date object methods like getMonth on it. Pretty sure the browser console would’ve already told you something like that, if only you had bothered to look. – C3roe Commented Jun 2, 2017 at 9:28
 |  Show 1 more ment

1 Answer 1

Reset to default 3

$.trim() will return a string, not a date.

You would need to cast back to a date object before you can do getMonth().

 var d = $.trim(oListItem.get_item('Begindatum'));
 alert(d);
 var m = new Date(d).getMonth() + 1;
 alert(m);
发布评论

评论列表(0)

  1. 暂无评论