scsitim
scsitim

Reputation: 57

Javascript date stops working on the first day of the month.

I have a date selector that auto fills the date input on my forms for yesterday, but on the first day of the month it just goes blank and fails to populate the date. I guess my code is missing the bit that tells it to go to the previous month if it's the first. I can't work it out. All help appreciated.

var today = new Date();
$(document).ready( function() {
    var now = new Date();
    var month = (now.getMonth() + 1);               
    var day = (now.getDate() - 1);
    if(month < 10) 
        month = "0" + month;
    if(day < 10) 
        day = "0" + day;
    var today = now.getFullYear() + '-' + month + '-' + day;
    $('#date').val(today);
});

Upvotes: 1

Views: 132

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

There is no "zeroth" day of a month. Try this:

var now = new Date(today.getFullYear(), today.getMonth(), today.getDate()-1);

By doing this, you are creating a new date object with the day being... zero. Won't that break it? Nope. The Date constructor is clever enough to figure out that the zeroth day of the current month is to be interpreted as the last day of the previous month.

Everything else should work, just get rid of the -1 on var day = ... line.

var today = new Date();
$(document).ready( function() {
    var now = new Date(today.getFullYear(), today.getMonth(), today.getDate()-1);
    var month = (now.getMonth() + 1);
    var day = now.getDate();
    if(month < 10) 
        month = "0" + month;
    if(day < 10) 
        day = "0" + day;
    var result = now.getFullYear() + '-' + month + '-' + day;
    $('#date').val(result);
});

Upvotes: 2

MrCode
MrCode

Reputation: 64526

You are correct, you can't just -1 the date and expect it to return the previous date. You need to call setDate() with the -1. This will update the date object.

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

Upvotes: 2

Related Questions