繁体   English   中英

JavaScript中的今天-30天

[英]Today's date -30 days in JavaScript

我需要获取今天的日期 -30 天,但格式为:“2016-06-08”

我试过setDate(date.getDate() - 30); -30 天。

我已经尝试过date.toISOString().split('T')[0]的格式。

两者都有效,但不知何故不能一起使用。

setDate()不返回Date对象,它返回自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。 您需要单独调用:

var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"

请注意,您最好为此使用诸如moment.js 之类的东西,而不是重新发明轮子。 然而,没有库的直接 JS 解决方案是这样的:

var date = new Date();
date.setDate(date.getDate() - 30); 

date设置为 30 天前。 (JS 会自动考虑闰年和滚动少于 30 天的月份,并进入上一年)

现在只需按照您的意愿输出它(让您更好地控制输出)。 请注意,我们在前面添加了一个“0”,以便小于 10 的数字以 0 为前缀

var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)

你是说这两行对你有用,你的问题是将它们结合起来。 这是你如何做到的:

 var date = new Date(); date.setDate(date.getDate() - 30); document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
 <div id="result"></div>

如果你真的想减去 30 天,那么这段代码很好,但如果你想减去一个月,那么显然这段代码不起作用,最好使用像其他人建议的那样的库 moment.js 而不是尝试自己实现。

 // Format date object into a YYYY-MM-DD string const formatDate = (date) => (date.toISOString().split('T')[0]); const currentDate = new Date(); // Values in milliseconds const currentDateInMs = currentDate.valueOf(); const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30; const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs); console.log(formatDate(currentDate)); console.log(formatDate(calculatedDate));

今天的日期 -30 天,格式如下:“YYYY-MM-DD”:

var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2021-02-05"

今天的日期 -30 天,但以这种格式获取所有天数:“YYYY-MM-DD”:

var daysDate = [];
for(var i = 1; i<= 30; i++) {
    var date = new Date();
    date.setDate(date.getDate() - i);
    daysDate.push(date.toISOString().split('T')[0]); // ["2021-02-05", "2021-02-04", ...]
}

简单地您可以根据时间戳进行计算

 var date = new Date(); // Current date console.log(date.toDateString()) var pre_date = new Date(date.getTime() - 30*24*60*60*1000); // You will get the Date object 30 days earlier to current date. console.log(pre_date.toDateString())

这里30*24*60*60*1000是指以毫秒为单位的时间差。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM