I need a little help from one of you Pros in here

I can usually figure stuff out on my own but this one is killing me at the moment.

var d = new Date(); var n = d.toString();

This one above works perfectly. However, the following only returns a large number.

var d = new Date(); var e = new Date().setDate(d.getDate()-1); var n = e.toString();

Any ideas?

Buddy

That’ a value in milliseconds.

You could do:

var today = new Date(),
    dayOfMonth = today.getDate(),
    yesterday = new Date(today.setDate(dayOfMonth-1));

console.log(today, yesterday);

Dates in JS tend to trip me up, so I normally use moment.js when I can

2 Likes

@James_Hibbard

AWESOME! That works great! I am working on a program that may or may not run everyday so getting at that previous day has been eluding me.

Thanks again!

Buddy

I second moment.js if you use dates in JS in more than a couple of places in your project. Getting yesterday’s date in moment is as simple as:

var yesterday = moment().subtract(1, 'days');
//or if you need it in native JS date format
yesterday = moment().subtract(1, 'days').toDate();
1 Like

I definitely liked what you shared as I am a HUGE fan of short compact code. I am sure it works in a normal setting.

However, in the platform I am working in it doesn’t work. :frowning:

Since I am one of their Alpha & Beta testers I suggested that they put this into their next update.

Thanks again!

Buddy

If it’s frontend code just include it in a script tag (moment is freely downloadable).

If you’re in a commonJS environment (node.js, Appcelerator Titanium, Browserify, etc) you can install it as a module and call moment like so:

var moment = require('moment');

It’s in a software development platform It will have to be added by the company.

Buddy

You’re setting the variable e not to the Date object, but to the return value of setDate. Try instead:

var e = new Date();
e.setDate(d.getDate()-1);

EDIT: Oops. I forgot the scroll down and somehow managed to not notice the plethora of other responses. :blush:

1 Like