0

Im trying to figure out how to pass a date in the format of yyyy-mm-dd through JS that I have done in PHP before, but PHP and JS being different in this sense. I am at a bit of a loss.

Heres how I did it in PHP:

var default_dob = strtotime(date('m/d/Y', time()) .' -18 year');
var dob = date('m/d/Y', default_dob);

essentially taking todays date, subtracting 18 years, and reformatting it so its mm/dd/yyyy for a date picker. Idealy I'd like to avoid adding in another plugin to my already big stack of JS. So if I can do this without the extra weight (outside of being able to plug it into maybe a ready made function Ill be happy)

1

3 Answers 3

1

This will alert the date in your required format exactly 18 years back.

var date = new Date(); 
date.setFullYear(date.getFullYear() - 18); 
alert(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate());
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

<script type="text/javascript">
$ss=  date('m/d/Y', strtotime('+18 year'));
?>
var default_dob = '<?php echo $ss;?>';
alert(default_dob);
</script>

Comments

0
// 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()

See also: MDN entry on the Date() object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.