JS中的PHP日期格式化

PHP date formating in JS

本文关键字:格式化 日期 PHP 中的 JS      更新时间:2023-09-26

我试图弄清楚如何通过JS传递yyyy-mm-dd格式的日期,这是我以前在PHP中做过的,但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堆栈中添加另一个插件。因此,如果我能在没有额外重量的情况下做到这一点(除了能够将其插入一个现成的函数之外,我会很高兴)

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

var date = new Date(); 
date.setFullYear(date.getFullYear() - 18); 
alert(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate());

试试这个

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

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