How to get yesterday date in node.js backend?

19,434

Solution 1

Try this:

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

Solution 2

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

Solution 3

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.

Share:
19,434
Shanthi
Author by

Shanthi

Updated on July 22, 2022

Comments

  • Shanthi
    Shanthi almost 2 years

    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 ?

    • Patrick
      Patrick almost 9 years
    • Salman
      Salman almost 9 years
      If we all could try to search first and post questions only if we don't find, that'd be great. And if we mark questions as duplicate instead of posting answers just to gain reps, that'd be great.
  • SuperBiasedMan
    SuperBiasedMan almost 9 years
    Please explain what your code does and why it will solve the problem. An answer that just contains code (even if it's working) usually wont help the OP to understand their problem. It's also recommended that you don't post an answer if it's just a guess. A good answer will have a plausible reason for why it could solve the OP's issue.
  • ChickenWing24
    ChickenWing24 over 8 years
    what if the current date is 1st of January 2015? would yesterday still be equal to 31st December 2014 following this method?
  • Osama Mohamed
    Osama Mohamed over 8 years
    @ChickenWing24 Yes, its.
  • Sanket Sarang
    Sanket Sarang about 4 years
    I tried this. A -1 on 1st of March makes it 31st of Feb. Definitely incorrect.
  • Herman J. Radtke III
    Herman J. Radtke III about 3 years
    I tried it with Node.js v12.21.0 and see the correct result: ``` Welcome to Node.js v12.21.0. Type ".help" for more information. > let d = new Date('2020-03-01') undefined > new Date(d.setDate(d.getDate() - 1)) 2020-02-28T00:00:00.000Z ```