Javascript 我想将日期格式更改为“yyyy-mm-dd”

Javascript 我想将日期格式更改为“yyyy-mm-dd”,javascript,php,jquery,codeigniter,Javascript,Php,Jquery,Codeigniter,在我的脚本标记中,var today以2019年9月7日周六00:00:00 GMT+0530印度标准时间日期格式显示,我想将此日期格式更改为yyyy-mm-dd格式 我的代码: <script> $(document).ready(function() { var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate

在我的脚本标记中,var today以2019年9月7日周六00:00:00 GMT+0530印度标准时间日期格式显示,我想将此日期格式更改为yyyy-mm-dd格式

我的代码:

<script>
    $(document).ready(function() {
        var date  = new Date();
        var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        console.log(today);
    });
</script>
我试着这样做:

<script>
    $(document).ready(function() {
        var date  = new Date();
        var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        var newDate = "<?php echo date("Y-m-d", strtotime(today)); ?>";
        console.log(newDate);
    });
</script>
如何使用strotime更改日期格式?

使用:

<script>
    $(document).ready(function() {
        var date  = new Date();
        var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        var newDate = "<?php echo date("Y-m-d"); ?>";
        console.log(newDate);
    });
</script>

当您已经具备了获取所需格式的所有功能时,不要使用服务器端逻辑:

<script>
    $(document).ready(function() {
        let today = new Date();
        let strToday = today.getFullYear() + "-" + today.getMonth() + "-" + today.getDay();
        console.log(strToday);
    });
</script>

只需格式化日期。别忘了getMonth是基于零的

const date=新日期; 常量mm=date.getMonth+1; const dd=date.getDate; 常量格式=[ date.getFullYear, 毫米>9?:“0”+毫米, dd>9?:“0”+dd ]。加入“-”;
console.logformat 编写一个函数来更改“yyyy-mm-dd”中的日期格式

JSFIDLE上的演示:


在一行代码中使用以下力矩可以实现代码行数较少的最佳效果

var today=时刻。格式为“YYYY-MM-DD”; console.logtoday
使用PHP获取今天的日期并更改格式


$origDate = "2019-01-15";

$newDate = date("m-d-Y", strtotime($origDate));
echo $newDate;

输出

01-15-2019

用js

  var date  = new Date();
  var year=date.getFullYear();
  var month= date.getMonth();
  var date=date.getDay();

 console.log(` ${day}:${month}:${year}`);


您可能应该看看在服务器(如PHP)和客户端(如JavaScript)上运行的代码之间的区别,以及它们如何相互作用提示:不像您想的那样,为什么要将JavaScript变量传递给PHP?@Andrea Manzi:110%肯定有重复的地方,但不是关于解析字符串的代码,而不仅仅是格式化误导性的标题?至于如何使用strotime更改日期格式你没有。今天是一个Javascript变量,PHP无法访问它。请参阅以获得更详细的解释。如果您使用PHP设置newDate,那么date和today完全是多余的。
  var date  = new Date();
  var year=date.getFullYear();
  var month= date.getMonth();
  var date=date.getDay();

 console.log(` ${day}:${month}:${year}`);