keeplearning
keeplearning

Reputation: 379

Unable to get current date time using javascript

var now = new Date();
var dateString = now.getMonth() + "-" + now.getDate() + "-" + now.getFullYear() + " "
+ now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

here month is not displayed correctly.

Example if output is december it prints november

now.getMonth() +1 would display the correct month.

I am looking for a more better approach.

My application has to choose between two radiobuttons.the first option should return the current system date and time and other returns date and time selected from jsp. On selecting either of the two options,it should return a date in a specific format to the controller.

Upvotes: 2

Views: 1343

Answers (3)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

getMonth() by definition returns month from 0 to 11.

If you are not used to this, you can change the prototype of a Date object:

Date.prototype.getFixedMonth = function(){
    return this.getMonth() + 1;
}

new Date().getFixedMonth(); //returns 12 (December)
new Date("January 1 2012").getFixedMonth //returns 1 (January)

But this is not recommended at all.


Another approach

You can do this too if you want:

Date.prototype._getMonth = Date.prototype.getMonth;
Date.prototype.getMonth = function(){       //override the original function
    return this._getMonth() + 1;
}

new Date().getMonth(); //returns 12 (December)
new Date("January 1 2012").getMonth //returns 1 (January)

Upvotes: 4

Alireza Masali
Alireza Masali

Reputation: 688

Here is the Function

 function GetTime_RightNow() {
        var currentTime = new Date()
        var month = currentTime.getMonth() + 1
        var day = currentTime.getDate()
        var year = currentTime.getFullYear()
        alert(month + "/" + day + "/" + year)
    }

Upvotes: 2

Swapnil
Swapnil

Reputation: 8318

getMonth() is supposed to return the Month as index from 0 to 11 (0 is January and 11 is December). So, what you're getting is the expected return value.

Upvotes: 2

Related Questions