Convert PHP date into javascript date format

后端 未结 8 853
误落风尘
误落风尘 2020-12-06 04:45

I have a PHP script that outputs an array of data. This is then transformed into JSON using the json_encode() function.

My issue

相关标签:
8条回答
  • 2020-12-06 04:46

    You should probably just use a timestamp

    $newticket['DateCreated'] = strtotime('now');
    

    Then convert it to a Javascript date

    // make sure to convert from unix timestamp
    var now = new Date(dateFromPHP * 1000);
    
    0 讨论(0)
  • 2020-12-06 04:46

    The most robust way is to extend your date object to parse strings as objects that your application can use. A quick example of parsing the mysql datetime string

    DateFromString(str){
     let months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
     let date = str.split(" ")[0];
     let time = str.split(" ")[1];
    
     let [Y, M, d] = [date.split("-")[0], date.split("-")[1], date.split("-")[2]];
     let [H, m, s] = [time.split(":")[0], time.split(":")[1], time.split(":")[2]];
    
     return {
      FullYear: Y,
      Month: M - 1,
      MonthString: months[M - 1],
      Date: d,
      Time: {Hour: H, Minute: m, Second: s},
     };
    }
    

    If you are inclined you may include a second parameter that describes the type of string being passed with a default value, and do a string test to determine if it is a unix timestamp or a javascript timestamp or a string, and then use the returned object to parse your date and times, this is a more rounded solution because it will allow you to build an interface that dynamically handles multiple date specifiers.

    0 讨论(0)
  • 2020-12-06 04:49

    If you want to be more precise with your timestamp, you should use microtime() instead of now().

    That gives you:

    echo round(microtime(TRUE)*1000);
    

    For a milisecond, javascript-like timestamp in php.

    0 讨论(0)
  • 2020-12-06 04:56

    Is very simple, I'm use this:

    new Date("<?= date('Y/m/d H:i:s'); ?>");
    
    0 讨论(0)
  • 2020-12-06 05:00

    It is pretty simple.

    PHP code:

    $formatted_date = $newticket['DateCreated'] =  date('Y/m/d H:i:s');
    

    Javascript code:

    var javascript_date = new Date("<?php echo $formatted_date; ?>");
    
    0 讨论(0)
  • 2020-12-06 05:06

    Javascript Date class supports ISO 8601 date format so I would recommend:

    <?php 
          date('c', $yourDateTime); 
          // or for objects
          $dateTimeObject->format('c');
    ?>
    

    documentation says that: format character 'c' is ISO 8601 date (added in PHP 5)
    example: 2004-02-12T15:19:21+00:00

    for more information: http://php.net/manual/en/function.date.php

    0 讨论(0)
提交回复
热议问题