如何在javascript中获取上一个日期 [英] How to get previous date in javascript
问题描述
我有一个日期,但我想从中获取上一个日期.我们如何使用 javascript 或 momentjs?
I have one date but i want to get previous date from that.How we can do using javascript or momentjs?
演示:https://stackblitz.com/edit/js-ykswiz?file=index.js
日期格式 dd-mm-yyyy.
date format dd-mm-yyyy.
示例:
var date1=new Date("08-06-2020");
console.log("Prev Date="+date1.getDate() - 1);// Prev Date=07-06-2020
var date2=new Date("01-06-2020");
console.log("Prev Date="+date2.getDate() - 1);// Prev Date=31-05-2020
var date3=new Date("01-01-2021");
console.log("Prev Date="+date3.getDate() - 1);// Prev Date=31-12-2020
在javascript中可以吗?
Is it possible in javascript?
推荐答案
首先,如果给new Date()
函数传递一个字符串,应该是这样的格式new Date('MM-dd-yyyy')
first, if you pass a string to the new Date()
function, it should be in this format new Date('MM-dd-yyyy')
所以前两位数字代表月份
so the first 2 digits represent the month
后两位代表日期
接下来的4位数字代表年份
the next 4 digits represent the year
so new Date("08-06-2020")
表示 August 06, 2020
而不是 June 08, 2020
so new Date("08-06-2020")
means August 06, 2020
not June 08, 2020
要获得某个日期的前一天,我们可以使用时刻减去1天,如下所示
to get the previous day of some date, we can use the moment to subtract 1 day like the following
var date1 = new Date('08-06-2020'); // Aug 06, 2020
var date11 = moment(date1).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date1 >> ${date1}`);
console.log(`date11 >> ${date11}`);
var date2 = new Date('01-06-2020'); // Jan 06, 2020
var date22 = moment(date2).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date2 >> ${date2}`);
console.log(`date22 >> ${date22}`);
希望能帮到你
这篇关于如何在javascript中获取上一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!