如何在Javascript或JQuery中获取上个月的最后一天

20
我有以下代码用于获取当前日期:

我有以下代码用于获取当前日期:

var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

var d = new Date();
var curr_date;
if (d.getDate() == 1)
{
    curr_date = d.getDate();
}
else
{
    curr_date = d.getDate() - 1;
}

var curr_month = d.getMonth() + 1; //months are zero based
var curr_year = d.getFullYear();
var message_day = curr_year + "_" + curr_month + "_" + curr_date;
var sql_day = month[curr_month - 1].substring(0,3) + curr_date.toString() + curr_year.toString();

if (curr_date == "1")
    {
         document.write(sql_day + " " + message_day);
    }

这对于获取当前日期非常有用,但现在如果是新月的开始,我需要获取上个月的最后一天。

现在这将产生:

Feb12012 2012_2_1
但我需要输出的是:
Jan312012 2012_1_31

谢谢

8个回答

49
var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.

现在d包含上个月的最后一天。 d.getMonth()d.getDate()将反映它。

这对任何包装C time.h的日期 API 都适用。


3
比油还滑! :-) - Patricia
简单就是性感! - Roberto Tellez Ibarra
我刚刚使用了这个解决方案,它很好用,但是如果你要使用ISO格式的输出,就需要小心时区。我不得不将所有的小时、分钟和秒都清零,以确保在转换为ISO格式时显示正确的日期... - Sean Rasmussen
7
将当月的第0天设为基准日期,即可得到上个月的最后一天。 - Claudio Bonfati

35

这对我来说完美地运作:

var date = new Date();
date.setDate(0);

date 现在包含上个月的最后一天。


缺少 d.setHours(-1); // 转到此日期开始之前的最后一小时。 - Roberto Tellez Ibarra
当上个月的最后一天是31号时,这个解决方案对我无效。 - habib
其他评论是误导性的。这种方法是有效的;您只需要包括时间并省略时区指示符(“Z”),如果您正在显式设置日期。例如:new Date('2023-01-15T00:00:00.000') - 有效, new Date('2023-01-15T00:00') - 有效, new Date('2023-01-15T00:00:00.000Z') - 无效, new Date('2023-01-15') - 无效。 - sfarbota

1

从我得到的答案中,大多数都未能捕获5月份的31天,因此我尝试了几个选项,以下是我想出来的。希望有些人会觉得这些有用。

const today = new Date()
const lastMonth = today.getMonth() === 0 ? 11 : today.getMonth() - 1
const year = lastMonth === 0 ? today.getFullYear - 1 : today.getFullYear

const lastDayOfLastMonth = new Date(year, lastMonth + 1, 0).getDate()
const lastDateTimeOfLastMonth = new Date(year, lastMonth + 1, 1)
const lastDateOfLastMonth = new Date(year, lastMonth + 1, 0).toLocaleDateString()

console.log(lastDayOfLastMonth) // eg 31
console.log(lastDateTimeOfLastMonth) // eg 2021-05-31T16:00:00.000Z
console.log(lastDateOfLastMonth) // eg 31/05/2021

0

只需从月份中减去一天:

 var today = new Date();
 var yesterday = new Date().setDate(today.getDate() - 1);

如果“date”属性(即月中的某一天)为1,则将其设置为零将给您一个表示上个月最后一天的日期。您的代码已经非常接近了;您只需构造一个新的Date实例即可:
 if (d.getDate() === 1)
    curr_date = new Date().setDate(0).getDate();

实际上你甚至不需要一个“if”语句:
 curr_date = new Date().setDate( d.getDate() - 1 ).getDate();

这对于月份中的任何一天都适用。


由于某些原因,我没有得到我期望的输出:http://jsfiddle.net/gT6eZ/1/ - some_bloody_fool

0

试一下这个

function dateLastMonth() {
            var date = new Date();
            date.setDate(0);
            return date.getDate().toString() + '/' + date.getMonth().toString() + '/' + date.getFullYear().toString();
        }

0
var lastdayoflastmonth = new Date();
lastdayoflastmonth.setMonth(lastdayoflastmonth.getMonth(), 0);
var firstdayoflastmonth = new Date();
firstdayoflastmonth.setDate(1);
firstdayoflastmonth.setMonth(firstdayoflastmonth.getMonth()-1);

-1

const today = new Date();
const date = new Date(Date.UTC(today.getFullYear(), today.getMonth(), 0, 0,0,0,0)).toISOString()
console.log(date)


1
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,以帮助他人理解这如何回答所提出的问题。您可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community

-3
const monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];                                       
let today = new Date();
let dd = today.getDate();

let mm = today.getMonth()+1;
let yyyy = today.getFullYear();
if(dd<10) 
{
    dd='0'+dd; 
} 
if(mm<10) 
{
    mm='0'+mm;
} 
dd = new Date(yyyy, mm-1, 0).getDate(); 

let month = '';                     
mm == 1 ? month = monthNames[monthNames.length - 1] : month = monthNames[mm-2];                                         
mm == 1 ? yyyy = yyyy - 1 : '';                                                                                 

let lastDay = month+'-'+dd+'-'+yyyy; 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接