如何在javascript变量中添加php日期?

时间:2017-10-13 07:33:15

标签: javascript php jquery

我正在尝试使用特殊格式嵌入日期,使用变量presentdate中的php代码,如下面的代码行

var dateFormatPHP = getDateFormat();
var formatToApplyPHP = "";

switch(dateFormatPHP)
{

    case "d-m-Y":
         formatToApplyPHP= "d/m/Y";
    break;

    case "m-d-Y":
        formatToApplyPHP= "m/d/Y";
    break;

    case "Y-m-d":
        formatToApplyPHP= "Y/m/d";
    break;

 }     


var presentdate = <?php echo date(formatToApplyPHP);?>

请帮助!!!

3 个答案:

答案 0 :(得分:0)

Javascript数据传输到PHP通常用XmlhttpRequest处理,所以创建php文件eg.date.php!将该格式作为param发送到该文件并获取响应数据。像这个例子

var dateFormatPHP = getDateFormat();
var formatToApplyPHP = "";

switch(dateFormatPHP)
{

    case "d-m-Y":
         formatToApplyPHP= "d/m/Y";
    break;

    case "m-d-Y":
        formatToApplyPHP= "m/d/Y";
    break;

    case "Y-m-d":
        formatToApplyPHP= "Y/m/d";
    break;

 }     

 $.get("date.php",{d:formatToApplyPHP},function(data) {
      console.log(data);
 });

date.php

<?php
   echo date($_GET['d']);
?>

答案 1 :(得分:-1)

formatToApplyPHP是Javascript变量,尝试使用PHP设置此变量,然后您可以使用此语句:

var presentdate = <?php echo date($formatToApplyPHP);?>

答案 2 :(得分:-2)

编辑:(这应该有用)

<script>  
var presentdate= <?php echo "date( ".formatToApplyPHP.");";?>  

console.log( presentdate);  

</script>