使用 Javascript 获取上一个日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9192956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:53:31  来源:igfitidea点击:

Getting Previous Date Using Javascript

javascriptjquery

提问by user1049997

I want to get the before six months date using javascript.

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

I am using the following method.

我正在使用以下方法。

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);

Is this the right way or any better way to get the last six months date.

这是获得过去六个月日期的正确方法还是任何更好的方法。

If this get fixed I want to apply this logic to get previous dates like last 2 months and last 10 years etc.

如果此问题得到解决,我想应用此逻辑来获取过去的日期,例如过去 2 个月和过去 10 年等。

If any body give the solution in jquery also very helpful to me. Thanks in advance.

如果任何机构在 jquery 中给出解决方案也对我很有帮助。提前致谢。

回答by Tx3

Add more functionality to the Date

为日期添加更多功能

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;
};

Usage

用法

var date = new Date();
/* get month back */
date.addDays(-30);

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

No need for extra libraries, if this is only thing you need regarding dates. You can also create more functions to the Date's prototype according to your needs.

不需要额外的库,如果这只是你需要的关于日期的东西。您还可以根据需要为 Date 的原型创建更多功能。

回答by J. Holmes

I would look into date.js. It's well tested and has a very fluent interface for manipulating dates and times in JavaScript.

我会研究date.js。它经过了很好的测试,并且有一个非常流畅的界面,用于在 JavaScript 中操作日期和时间。

An example of using date.js:

一个使用 date.js 的例子:

(6).months().ago()

回答by pete

Try:

尝试:

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());