How to get yesterday date in node.js backend?

走远了吗. 提交于 2019-12-03 16:15:11

Try this:

var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!

I would take a look at moment.js if you are interested in doing calculations with dates, there are many issues you can run into trying to do it manually or even with the built in Date objects in JavaScript/node.js such as leap years and daylight savings time issues.

http://momentjs.com/

For example:

var moment = require('moment');
var yesterday = moment().subtract(1, 'days');
console.log(yesterday.format());

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

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);

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;
}

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)

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!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!