user663724
user663724

Reputation:

JavaScript : displaying Yesterdays Date in JavaScript

I was trying to display Yesterday Date on click of the button , but why its showing Date as "2013-6-0" instead of 2013-05-31

Could anybody please tell me what i was doing wrong

<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{

var d = new Date();
var curr_date = d.getDate()-1;
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var yesterday = curr_year + "-" + curr_month + "-" + curr_date ;

document.write(yesterday);

}
</script>
</head>
<body>


<p id="demo">Click Button to Display Yesterday Date</p>

<button type="button" onclick="displayDate()">Display Date</button>

</body>
</html> 

Upvotes: 1

Views: 6120

Answers (4)

Bae Cheol Shin
Bae Cheol Shin

Reputation: 1528

function displayDate()
{
    var today = new Date();
    today.setDate(today.getDate()-1);
    var yyyy = today.getFullYear().toString();
    var mm = (today.getMonth()+1).toString();         
    mm = mm.length==2?mm:"0"+mm;
    var dd = today.getDate().toString();
    dd = dd.length==2?dd:"0"+dd;
    var yesterday = yyyy+"-"+mm+"-"+dd;

    document.write(yesterday);
}

Upvotes: 0

Diode
Diode

Reputation: 25135

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

var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

You should update and then reference the date from which you've subtracted 1 day:

var d = new Date();

d.setDate(d.getDate() - 1); // <-- add this to make it "yesterday"

var curr_date = d.getDate(); // <-- don't subtract 1 anymore
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();

DEMO

Upvotes: 4

ChrisP
ChrisP

Reputation: 5942

Your code simply takes a day number (like 1, 2, ...) and subtracts one from it. Why would you expect that to automatically roll the day back to the previous month?

You can generate new dates by subtracting milliseconds from a given date. Try this:

var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);

Upvotes: 1

Related Questions