Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript获取以前的日期_Javascript_Jquery - Fatal编程技术网

使用Javascript获取以前的日期

使用Javascript获取以前的日期,javascript,jquery,Javascript,Jquery,我想使用javascript获取六个月前的日期 我使用以下方法 var curr = date.getTime(); // i will get current date in milli seconds var prev_six_months_date = curr - (6* 30 * 24 * 60* 60*1000); var d = new Date(); d.setTime(prev_six_months_date); 这是获得最后六个月约会的正确方式还是更好的方式 如果这个问题得

我想使用javascript获取六个月前的日期

我使用以下方法

var curr = date.getTime(); // i will get current date in milli seconds
var prev_six_months_date = curr - (6* 30 * 24 * 60* 60*1000);
var d = new Date();
d.setTime(prev_six_months_date);
这是获得最后六个月约会的正确方式还是更好的方式

如果这个问题得到解决,我想应用这个逻辑来获得以前的日期,比如最近2个月和最近10年等等

如果有人在jquery中给出解决方案,对我也很有帮助。 提前谢谢。

我会调查的。它经过了很好的测试,有一个非常流畅的界面,可以用JavaScript操作日期和时间

使用date.js的示例如下:

(6).months().ago()

为日期添加更多功能

Date.prototype.addDays = function (n) {
    var time = this.getTime();
    var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
    this.setTime(changedDate.getTime());
    return this;
};
var date = new Date();
/* get month back */
date.addDays(-30);

/* get half a year back */
date.addDays(-30 * 6);
用法

Date.prototype.addDays = function (n) {
    var time = this.getTime();
    var changedDate = new Date(time + (n * 24 * 60 * 60 * 1000));
    this.setTime(changedDate.getTime());
    return this;
};
var date = new Date();
/* get month back */
date.addDays(-30);

/* get half a year back */
date.addDays(-30 * 6);
不需要额外的库,如果这是关于日期的唯一需要。您还可以根据需要为Date的原型创建更多功能。

试试:

var curr = new Date();
var prev_six_months_date = new Date(curr);
var prev_two_months_date = new Date(curr);
var prev_ten_years_date = new Date(curr);
prev_six_months_date.setMonth(curr.getMonth() - 6);
prev_two_months_date.setMonth(curr.getMonth() - 2);
prev_ten_years_date.setFullYear(curr.getFullYear() - 10);
console.log(prev_six_months_date.toString());
console.log(prev_two_months_date.toString());
console.log(prev_ten_years_date.toString());
console.log(curr.toString());

由于您将其标记为jQuery,因此可以将
date.getTime()
替换为
$.now()
。很久没有出现这个问题了,但仍然:
var d=new date()
d.setMonth(d.getMonth()-6)
类似地,您可以使用
setYears()
setDate()
来增加功能。