【问题标题】:PHP date formating in JSJS中的PHP日期格式
【发布时间】:2013-09-02 09:38:22
【问题描述】:

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

【问题讨论】:

标签: javascript php date datetime


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:
      // 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 entry on the Date() object

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多