Saxman Saxman - 2 years ago 73
Javascript Question

setDate() set the wrong date on 31st?

This is very weird I don't know what I'm doing wrong. I have a function to grab the date (i.e in this format:

), here's the function:

function checkDate(input){
var d = new Date();
var dspl = input.split("/");

if(dspl.length != 3)
return NaN;



if(dspl[2].length == 2)
else if(dspl[2].length == 4)
return NaN;

var dt = jsToMsDate(new Date(d));
return dt;

If I enter any date of the month, it would parse the date correctly, but if I enter 31st, i.e
, then it would turn into
. I'm not sure what to do and not really sure where the problem might be.

Answer Source

JavaScript's Date objects allow you to give invalid combinations of months and days; they automagically correct those for you (so for instance, if you set the day of the month to 31 when the month is June, it automatically makes it July 1st). That means if you set the fields individually, you can run into situations where that automagic correction gets in your way.

In your case, if you're going to set all three of those fields, you're better off using the form of the Date constructor that accepts them as arguments:

var dt = new Date(year, month, day);

(If you want hours, minutes, seconds, and milliseconds, you can add them as parameters as well.)

So looking at your code, an off-the-cuff update:

function checkDate(input){
    var year, month, day, d, dt;
    var dspl = input.split("/");

    if(dspl.length != 3)
        return NaN;

    year  = parseInt(dspl[2], 10);
    month = parseInt(dspl[0], 10) - 1;
    day   = parseInt(dspl[1], 10);
    if (isNaN(year) || isNaN(month) || isNaN(day)) {
        return NaN;

    if (year < 100) {
        year += 2000;

    d = new Date(year, month, day);

    var dt = jsToMsDate(d);
    return dt;

Some other notes on that update:

  • It's best to use parseInt to parse numbers from end users, and to always specify the radix (10 for decimal). (No, parseInt is not slower than Number or the unary + trick. People assume it is, but it isn't.)
  • No need to muck about with strings to add 2000 to years given with only two digits. But you can if you like. Note I weakened the validation there, allowing one-digit years for (say) 2001 and three-digit years for (say) 300 AD. So if you need it to be that strong, you'll need to readjust that.
  • No need to feed the date instance into new Date() again.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download