How to get yesterday date in node.js backend?

2019-03-30 09:32发布

I am using date-format package in node back end and I can get today date using

var today = dateFormat(new Date());

In the same or some other way I want yesterday date. Still I did't get any proper method. For the time being I am calculating yesterday date manually with lot of code. Is there any other method other then writing manually ?

7条回答
Fickle 薄情
2楼-- · 2019-03-30 09:44

you can also change Hour,Minute,seconds and milliseconds attributes of time object like this.

var date = new Date();
    date.setDate(date.getDate()-1);
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(seconds);
    date.setMilliseconds(milliseconds);
查看更多
劫难
3楼-- · 2019-03-30 09:44

Try Library called node-datetime

var datetime = require('node-datetime');
var dt = datetime.create();
// 7 day in the past
dt.offsetInDays(-1);
var formatted = dt.format('Y-m-d H:M:S');
console.log(formatted)
查看更多
虎瘦雄心在
4楼-- · 2019-03-30 09:51

Extract yesterday's date from today

//optimized way 
        var yesterday = new Date();
        yesterday.setDate(yesterday.getDate()-1);
        console.log(yesterday) // log yesterday's date 


//in-detail way 
        var today = new Date();
        var yesterday = new Date();
        yesterday.setDate(today.getDate()-1);
        console.log(yesterday) // log yesterday's date
查看更多
SAY GOODBYE
5楼-- · 2019-03-30 09:58

Try this:

var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!
查看更多
▲ chillily
6楼-- · 2019-03-30 09:59

To get the string in a format familiar to people

// Date String returned in format yyyy-mm-dd
function getYesterdayString(){
    var date = new Date();
    date.setDate(date.getDate() - 1);
    var day = ("0" + date.getDate()).slice(-2);
    var month = ("0" + (date.getMonth() + 1)).slice(-2); // fix 0 index
    return (date.getYear() + 1900) + '-' + month + '-' + day;
}
查看更多
Explosion°爆炸
7楼-- · 2019-03-30 10:03

Date class will give the current system date and current_ date - 1 will give the yesterday date.

Eg:

var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!
查看更多
登录 后发表回答