简体   繁体   English

从 JavaScript 中的当前日期获取上个月的第一个日期

[英]Getting the previous month's first date from current date in JavaScript

Please anyone share the code to find the previous month's first date from current date in JavaScript.请任何人分享代码以在 JavaScript 中找到从当前日期开始的上个月的第一个日期。 For example, if the current date is 25th Jan 2009, I should get 1st Dec 2008 as result.例如,如果当前日期是 2009 年 1 月 25 日,我应该得到 2008 年 12 月 1 日作为结果。

Straightforward enough, with the date methods :很简单,使用日期方法

  var x = new Date();
  x.setDate(1);
  x.setMonth(x.getMonth()-1);

Simplest way would be:最简单的方法是:

var x = new Date();
x.setDate(0); // 0 will result in the last day of the previous month
x.setDate(1); // 1 will result in the first day of the month

Deals with updating year when moving from January to December处理从 1 月到 12 月移动时更新年份

 var prevMonth = function(dateObj) { var tempDateObj = new Date(dateObj); if(tempDateObj.getMonth) { tempDateObj.setMonth(tempDateObj.getMonth() - 1); } else { tempDateObj.setYear(tempDateObj.getYear() - 1); tempDateObj.setMonth(12); } return tempDateObj }; var wrapper = document.getElementById('wrapper'); for(var i = 0; i < 12; i++) { var x = new Date(); var prevDate = prevMonth(x.setMonth(i)); var div = document.createElement('div'); div.textContent = "start month/year: " + i + "/" + x.getFullYear() + " --- prev month/year: " + prevDate.getMonth() + "/" + prevDate.getFullYear() + " --- locale prev date: " + prevDate.toLocaleDateString(); wrapper.appendChild(div); }
 <div id='wrapper'> </div>

Check this link:检查此链接:

http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/ http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/

EDIT: I have drummed up an example:编辑:我鼓起一个例子:

Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
d.setDate(1);
return d;
}

$(document).ready(function() {
    var d = new Date();
    alert(d.SubtractMonth(1));
});

This worked for me这对我有用

var curDateMonth = new Date();
var prvDateMonth = new Date(curDateMonth.getFullYear(),curDateMonth.getMonth()-1,curDateMonth.getMonth());
console.log(curDateMonth.toLocaleString('en-US', { month: 'long' }) +' vs '+ prvDateMonth.toLocaleString('en-US', { month: 'long' }));

Important Note: Some of the answers using setMonth() here are wrong :重要提示:这里使用setMonth()一些答案是错误的

One liners for use in 2019 (using ES6 syntax; supported by all major browsers and Node): 2019 年使用的一个衬垫(使用 ES6 语法;所有主要浏览器和 Node 都支持):

    const date = new Date().toISOString(); // "2019-09-18T13:49:12.775Z"
    const [yyyy, mm, dd, h, i, s] = date.split(/T|:|-/);


    // previous month's last day
    const prev = new Date(new Date().setDate(0)).toISOString();
    const [pyyyy, pmm] = prev.split(/T|:|-/);

Note that Array destructuring allows you to skip parts:请注意,数组解构允许您跳过部分:

    const date = new Date().toISOString();
    const [, , dd, , i] = date.split(/T|:|-/);

Explanation : The code above gets the ISO date 2019-09-18T13:49:12.775Z and splits it on : or - or T which returns an array [2019, 09, 18, 13, 49, 12] which then gets destructured .说明:上面的代码获取 ISO 日期2019-09-18T13:49:12.775Z并将其拆分为: or -T ,它返回一个数组[2019, 09, 18, 13, 49, 12]然后被解构

Using setMonth() is wrong:使用setMonth()是错误的:

date = new Date("Dec 31, 2019")
date.setMonth(date.getMonth() - 1);
date; // Dec 1, 2019!

To get 00:00:00 am of previous month use this:要获得上个月的 00:00:00 am,请使用以下命令:

let d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
d.setHours(0,0,0,0);
const lastMonthStart = new Date(d);

Hope this helps!!希望这可以帮助!!

//  Previous Month Detail
let prevStartDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1, 1);
console.log(prevStartDate);
let preEndDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1 + 1, 0);
console.log(preEndDate);
//Current Month Detail
let cStartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
console.log(cStartDate);
let cEndDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0);
console.log(cEndDate);
//Next Month Detail
let nStartDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 1);
console.log(nStartDate);
let nendDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1 + 1, 0);
console.log(nendDate);

//just try this will work fine //试试这个就可以了

let date = new Date();
let month = new Date().getMonth();
let prevMonth = date.setMonth(month - 1)
let formatPrevMonth = new Date(date.setMonth(month - 1));

console.log(formatPrevMonth)

Below is the code which worked for me下面是对我有用的代码

var currentMonth = date.getMonth()+1; var currentMonth = date.getMonth()+1; Here, first we assigned the getMonth() Ftn to a variable and incremented it by 1. Then var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate();在这里,首先我们将 getMonth() Ftn 分配给一个变量并将其递增 1。然后 var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate(); document.getElementById("p3").innerHTML = "Today,s date:"+current_date; document.getElementById("p3").innerHTML = "今天,s 日期:"+current_date;

None: None of the above techniques worked for me...无:上述技术都不适合我......

This can easily be achieved by creating a Date object based on the input date object and changing the date to 1, decrementing the year if it was January and decrementing the month (modulo 12).这可以通过根据输入日期 object 创建一个Date object 并将日期更改为 1 来轻松实现,如果是一月则递减年份并递减月份(模 12)。 An important addition to it is to subtract the offset as well.一个重要的补充是减去偏移量。

 function getFirstOfPreviousMonth(date) { let result = new Date(date.getFullYear() - (date.getMonth()? 0: 1), (date.getMonth() + 11) % 12, 1); return new Date(result.getTime() - result.getTimezoneOffset() * 60000); } console.log(getFirstOfPreviousMonth(new Date())); console.log(getFirstOfPreviousMonth(new Date(2009, 0, 25)));

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

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