chris
chris

Reputation: 36937

PHP date formating in JS

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)

Upvotes: 0

Views: 168

Answers (3)

DaveRandom
DaveRandom

Reputation: 88647

// 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

Upvotes: 0

Padmanathan J
Padmanathan J

Reputation: 4620

Try this

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

Upvotes: 0

sam_codes
sam_codes

Reputation: 191

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());

Upvotes: 1

Related Questions