Js计算上月与当前时间戳的差值

本文介绍了一种使用JavaScript来计算并获取上个月开始和结束日期的方法。通过设置日期和月份,可以准确地得到上个月的具体时间范围,这对于需要按月统计的数据应用非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//获得上月时间
initLastMonthTime:function (){


var now = new Date(); //当前日期
var nowYear = now.getFullYear(); //当前年
var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
var lastMonth = lastMonthDate.getMonth();





//获得上月开始时间
var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
var formatMonth=(new Date(lastMonthStartDate).getMonth() + 1)<10? "0"+(new Date(lastMonthStartDate).getMonth() + 1):new Date(lastMonthStartDate).getMonth() + 1;
var formatDate=new Date(lastMonthStartDate).getDate()<10? "0"+new Date(lastMonthStartDate).getDate():new Date(lastMonthStartDate).getDate();

var lastStartTime=new Date(lastMonthStartDate).getFullYear() + '-' + formatMonth + '-' + formatDate ;





//获得上月结束时间
var lastMonthEndDate = new Date(nowYear, lastMonth, dataStatistics.getMonthDays(lastMonth));
var formatEndMonth=(new Date(lastMonthEndDate).getMonth() + 1)<10? "0"+(new Date(lastMonthEndDate).getMonth() + 1):new Date(lastMonthEndDate).getMonth() + 1;
var formatEndDate=new Date(lastMonthEndDate).getDate()<10? "0"+new Date(lastMonthEndDate).getDate():new Date(lastMonthEndDate).getDate();

var lastEndTime=new Date(lastMonthEndDate).getFullYear() + '-' +formatEndMonth + '-' + formatEndDate;


},



//获得某月的天数
getMonthDays:function (lastMonth){

var now = new Date(); //当前日期
var nowYear = now.getYear(); //当前年
var monthStartDate = new Date(nowYear, lastMonth, 1);
var monthEndDate = new Date(nowYear, lastMonth + 1, 1);
var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
return days;
},



//进行时间计算
var nowDate=new Date();
var strDateS = new Date(lastStartTime);
var strDateE = new Date(lastEndTime);
var last_start=(nowDate-strDateS)/(1000*3600*24);
var last_end=(nowDate-strDateE)/(1000*3600*24);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值