Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get date 30 days ago [duplicate]

I am trying to populate two date input fields, one with today's date and one with the date 30 days ago(last month).

I am getting an error in my console: priordate.getDate is not a function

Here is my code, not sure what I am doing wrong:

//today's date

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;

//30 days ago

var beforedate = new Date();
var priordate = new Date().setDate(beforedate.getDate()-30);
var dd2 = priordate.getDate();
var mm2 = priordate.getMonth()+1;//January is 0, so always add + 1
var yyyy2 = priordate.getFullYear();
if(dd2<10){dd2='0'+dd2};
if(mm2<10){mm2='0'+mm2};
var datefrommonthago = yyyy2+'-'+mm2+'-'+dd2;

// Set inputs with the date variables:

$("#fromdate").val(datefrommonthago);
$("#todate").val(today);
like image 880
Bruno Avatar asked Feb 03 '26 15:02

Bruno


2 Answers

You'll instead want to use:

var priordate = new Date(new Date().setDate(beforedate.getDate()-30));

if you want it on one line. By using:

new Date().setDate(beforedate.getDate()-30);

you're returning the time since epoch (a number, not a date) and assigning it to priordate, but it's not a Date anymore and so does not have the getDate function.

like image 123
Nick stands with Ukraine Avatar answered Feb 05 '26 08:02

Nick stands with Ukraine


This is because setDate() returns a number, not a Date Object.

In any I case I'd strongly recommend using momentjs or date-fns as the internal Date object in JavaScript is broken in all kind of ways. See this talk: https://www.youtube.com/watch?v=aVuor-VAWTI

like image 45
marvinhagemeister Avatar answered Feb 05 '26 08:02

marvinhagemeister