Richard N
Richard N

Reputation: 925

HTML input prepopulate date

Am rediscovering HTML after quite some time.

I am using just HTML and javascript along with Salesforce. I have two date input fields. I was curious to see if there is any easy way to populate these fields with: a. Today's date b. Date 6 months before today.

<input type="text" id="toDate" size="10" onmouseover="initialiseCalendar(this, 'toDate')"/> 

Thanks, Calvin

Upvotes: 5

Views: 4282

Answers (2)

Mathew Thompson
Mathew Thompson

Reputation: 56459

The following JavaScript sets the value of your textbox to today's date, in format yyyy-mm-dd. See how I add 1 to the month? getMonth() returns 0-11 for current month, so 1 is added to it:

var today = new Date();
document.getElementById("toDate").value = today.getFullYear() + "-" +
    parseInt(today.getMonth()+1) + "-" + ​​​​​​today.getDate();​​​​​

DEMO: Fiddle

It is worth noting though that if the month or day are lower than 10, you'll only get one digit for each of them. Let me know if this is an issue.

EDIT: To get 6 months from today, use:

var today = new Date();
var past = today.setMonth(today.getMonth() - 6);

Upvotes: 4

MaxArt
MaxArt

Reputation: 22647

Populate with today's date:

var today = new Date();
document.getElementById("toDate").value = today.getFullYear() + "-"
        + String(today.getMonth() + 101).slice(-2) + "-"
        + String(today.getDate() + 100).slice(-2);

6 month in the past:

var past = new Date();
past.setMonth(past.getMonth() - 6); //
document.getElementById("toOldDate").value = past.getFullYear() + "-"
        + String(past.getMonth() + 101).slice(-2) + "-"
        + String(past.getDate() + 100).slice(-2);

Upvotes: 3

Related Questions