// Left pad a string to the specified length using the specified character
function padLeft(str, length, char)
{
// Make sure args really are strings and that the length is a positive
// number. If you don't do this concatenation may do numeric addition!
str = String(str);
char = String(char) || ' '; // default to space for pad string
length = Math.abs(Number(length));
if (isNaN(length)) {
throw new Error("Pad length must be a number");
}
if (str.length < length) {
// Prepend char until the string is long enough
while (str.length < length) {
str = char + str;
}
// Make sure the string is the requested length
return str.slice(length * -1);
} else {
// The string is already long enough, return it
return str;
}
}
// Get the current date/time
// This is local to the browser, so it depends on the user's system time
var default_dob = new Date();
// Subtract 18 years
default_dob.setFullYear(default_dob.getFullYear() - 18);
// Format the string as you want it. PHP's d and m formats add leading zeros
// if necessary, in JS you have to do it manually.
var dob = padLeft(default_dob.getMonth(), 2, '0') + '/'
+ padLeft(default_dob.getDate(), 2, '0') + '/'
+ default_dob.getFullYear()
另请参阅:对象上的 MDN 条目Date()