We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# currentDate.getMonth(); returns wrong month

on
Medium Priority
2,902 Views
When I use the below code, I get "9/20/2006 1:07 AM".  I checked my system time and all is well.  It's October, so why is it returning 9?

function insertAtCursor(myField) {
var myValue;
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
myValue = month + "/" + day + "/" + year + " ";

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();

var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

if (minutes < 10)
minutes = "0" + minutes;

myValue += hours + ":" + minutes + " " + suffix;
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
Comment
Watch Question

## View Solution Only

Commented:
The javascript components all start from 0. so january would return '0' and not 1. Just a traditional way how array's behave. the index starts from 0, instead of 1

this should help

http://www.w3schools.com/jsref/jsref_obj_date.asp

http://www.tizag.com/javascriptT/javascriptdate.php

Gary

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Thanks harshgrover.  I use arrays a lot and I understand starting from 0, but that's just stupid.  Who would make a date function to get the current month and start it from 0?  The least they could do is be consistent and have getDate() act the same way.

Commented:
naw, i might be wrong, but i thought all the calendars in java behave the same, whether it is GregorianCalendar, java.util.Date etc. if you want to get the number of the month, they would all return 0 for January :)...i guess we programmers dont really care a lot about how things function in the real world ;)
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile