0

我试图弄清楚如何以yyyy-mm-dd我之前在 PHP 中完成的 JS 格式传递日期,但 PHP 和 JS 在这个意义上是不同的。我有点不知所措。

下面是我在 PHP 中的做法:

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

本质上是取今天的日期,减去 18 年,然后重新格式化它,使其mm/dd/yyyy成为日期选择器。理想情况下,我想避免在我已经很大的 JS 堆栈中添加另一个插件。因此,如果我可以在没有额外重量的情况下做到这一点(除了能够将其插入可能是现成的功能之外,我会很高兴)

4

3 回答 3

1

这将以您所需格式的日期提醒您正好 18 年前的日期。

var date = new Date(); 
date.setFullYear(date.getFullYear() - 18); 
alert(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate());
于 2013-09-02T09:49:12.090 回答
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()

另请参阅:对象上的 MDN 条目Date()

于 2013-09-02T09:53:05.123 回答
0

尝试这个

<script type="text/javascript">
$ss=  date('m/d/Y', strtotime('+18 year'));
?>
var default_dob = '<?php echo $ss;?>';
alert(default_dob);
</script>
于 2013-09-02T09:53:10.907 回答