【问题标题】:Getting day before on Javascript提前一天使用 Javascript
【发布时间】:2017-05-03 21:33:49
【问题描述】:

我正在尝试获取日期之前的一个月中的哪一天,这就是我所拥有的

var date =  new Date();
var day = date.getDay();
var month = date.getMonth() + 1;
var year = date.getFullYear();

var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 3);
var dayBefore = yesterday.getDay();
var MonthBefore = yesterday.getMonth() + 1;

在昨天的日志中我得到了

 Sun Apr 30 2017 16:24:33 GMT-0500

不是昨天,因为我试图获取当前月份的前一天,但我得到了上个月,现在我想获取该日期的日期和月份,所以我使用 getDate() 和 getMonth( ),我用

正确地得到月份
 MonthBefore = yesterday.getMonth() + 1;

这给了我 4(4 月),但在第 (30) 天,我使用

得到 0
dayBefore = yesterday.getDay();

这里是 jsfiddle:https://jsfiddle.net/4pf7bczv/

【问题讨论】:

  • 这个问题有点不清楚。你只是想得到昨天吗?那是asked and answered here。但是您的问题继续说有关本月前一天的内容,这有点不清楚。你想要上个月的最后一天吗?这已被多次询问和回答,including here
  • 这真的是Add +1 to current date的翻版,换个符号就好了。顺便说一句,yesterday.setDate(date.getDate() - 3) 会将日期设置为 3 天前,而不是 1。

标签: javascript date


【解决方案1】:

getDay 返回星期几。 getDate 返回月份中的哪一天。

试试这个:

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

var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 3);
var dayBefore = yesterday.getDate();
var MonthBefore = yesterday.getMonth() + 1;


console.log(date)
console.log(yesterday)
console.log(month + '/' + day + '/' + year + " 11:59 pm")
console.log(MonthBefore + '/' + dayBefore + '/' + year + " 12:00 am")

console.log(yesterday.getDate());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

【讨论】:

  • @RobG 实际上我以前没有这样做过(不确定它在工具栏上的确切位置)。我已经更新了它。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
相关资源
最近更新 更多