How to get yesterday date in node.js backend?

后端 未结 8 973
误落风尘
误落风尘 2021-02-09 14:00

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

相关标签:
8条回答
  • 2021-02-09 14:19

    Try this:

    var d = new Date(); // Today!
    d.setDate(d.getDate() - 1); // Yesterday!
    
    0 讨论(0)
  • 2021-02-09 14:20

    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)
    
    0 讨论(0)
  • 2021-02-09 14:20

    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
    
    0 讨论(0)
  • 2021-02-09 14:23

    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());
    
    0 讨论(0)
  • 2021-02-09 14:34

    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!
    
    0 讨论(0)
  • 2021-02-09 14:41

    var date=new Date();
    var date=new Date(date.setDate(date.getDate()-1));
    console.log(date);

    This will give you same Date format, but not tested for edge case scenarios.

    0 讨论(0)
提交回复
热议问题