【问题标题】:trying to encage getDate() inside a var试图将 getDate() 包含在 var 中
【发布时间】:2015-11-29 18:31:18
【问题描述】:

有人可以帮我理解为什么这在地球上不起作用?

    document.write('messing with the dates: <br>')
    var nowDate = new Date();
    var currentDay = nowDate.getDate();
    nowDate.setDate(currentDay + 1);
    document.write('if it\'s not inside a variable, it\'s nice and tidy: ' + nowDate.getDate() + '<br>');

    var tomorrow = (nowDate.setDate(currentDay + 1));
    document.write('but as soon as I put it inside a var, it becomes terrible: ' + tomorrow);

    document.write('and this is not even working' + tomorrow.getDate());

【问题讨论】:

  • 什么“不起作用”?你期待发生什么?实际发生了什么?
  • var tomorrow = (nowDate.setDate(currentDay + 1)); 不等于 var tomorrow = nowDate.getDate() 为什么不使用后者?看来这就是你想要的。
  • 我没有使用 getDate() 因为我已经知道日期,我想修改日期。
  • 这很好用:nowDate.setDate(currentDay + 1); document.write(nowDate.getDate()); 这不行:var tomorrow = nowDate.setDate(currentDay + 1); document.write( tomorrow); 这是问题所在,我不明白为什么。

标签: javascript date var getdate


【解决方案1】:

setDate 做了两件事,更改日期对象本身,并返回自 1970 年 1 月 1 日 00:00:00 UTC 结果日期以来的毫秒数。

tomorrow你的号码是多少

我想你应该这样使用它来实现你想要做的事情:

var tomorrow = new Date((nowDate.setDate(currentDay + 1)))

【讨论】:

  • var tomorrow = nowDate.setDate(currentDay + 1); document.write(tomorrow); 返回 1448918139765 如果我这样做 document.write(tomorrow.getDate()); 没有任何反应。为什么??!
  • 可以使用new Date() 工作!!非常感谢你!!但是现在有人可以解释一下为什么var tomorrow = nowDate.setDate(currentDay + 1); 是错误的,为什么你应该写var tomorrow = new Date((nowDate.setDate(currentDay + 1)));
  • 正如我所说,因为 nowDate.setDate(currentDay + 1) 返回自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数 - 这就是 tomorrow 得到的
猜你喜欢
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 2017-05-14
  • 2016-03-20
  • 1970-01-01
  • 2011-12-24
相关资源
最近更新 更多