28

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

My issue is I have a date within my array and it's not in the correct JavaScript format. How can I convert this within PHP so it is?

$newticket['ThreadID'] =  $addticket;
$newticket['Subject'] =  $subject;
//$newticket['DateCreated'] =  date('d-m-Y G:H');

Instead of the above for the date I need the equivalent of the JavaScript function

new Date()

When I output the above I get the following "Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time)" However, If I format my PHP date to be the same, then JavaScript rejects it. Confused...

Can anyone help?

10 Answers 10

41

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);
Sign up to request clarification or add additional context in comments.

3 Comments

the javascript date format is: Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time) not a timestamp
No, there are multiple ways of instantiating a date object, including a timestamp: w3schools.com/jsref/jsref_obj_date.asp
@LeeTee The easiest and most transportable format is a timestamp, which you can then convert to whatever you want.
19

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

4 Comments

This works very well with Javascript new Date(); good answer!
Ecmascript does not support full ISO 8601. only a simplified version of it
@belst sources?
262.ecma-international.org/15.0/#sec-date-time-string-format > ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format.
7

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; ?>");

Comments

1

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.

Comments

1

Is very simple, I'm use this:

new Date("<?= date('Y/m/d H:i:s'); ?>");

2 Comments

@RichardSocker <?= is short for <?php echo ...
Thanks man, new thing to me, actually I tried it but I got 500 error maybe cause another error. :)
1

An improvement or simplification of @jeremyharris answer would be this one:

DateTime objects in PHP have the getTimestamp() format, use it and multiply the value by 1000:

<?php 
    $phpDateTimeStamp = new Date('Y/m/d H:i:s')->getTimestamp() * 1000; 
?>

// JavaScript
let phpDateTimeStamp = 'YOUR_PHP_VARIABLE';
let startTime = new Date(parseInt(phpDateTimeStamp));

4 Comments

// in JavaScript we have to cast the php timestamp to int let startTime = new Date(parseInt(phpDateTimeStamp));
phpDateTimeStamp is not defined.
@mickmackusa in JS code, phpDateTimeStamp should be a variable coming from a $phpDateTimeStamp PHP variable.
Your code is not implementing this. This makes your answer misleading/confusing for readers.
1

maybe this code inspire you I just created that I need.

const convertDate = (
    time,
    format = "h:i" // Y-m-d H:i:s 
) => {
    /**
     * Asume the date is 2023-09-01 23:11:01 
     * F = September ; Month as text 
     * M  = Sep ; Month with 3 chars 
     * m  = 08 ; Month with 3 chars 
     * j = 1   : day without zero 
     * d = 01   : day with zero 
     * D = Fri  : day with 3 chars
     * l = Friday  : day with text
     * Y = 2023 : Year Full
     * y = 23  : Year short
     * H = 23  : time for 24 hours 
     * h = 11  : time for 12 hours 
     * i = 11  : minute  
     * s = 01  : Second 
     * 
     */
    if (!time) time = new Date();
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    const dt = new Date(time);
    const F = months[dt.getMonth()];
    const M = months[dt.getMonth()].substr(-2);
    const m = `0${dt.getMonth()}`.substr(-2);
    const j = dt.getDay();
    const d = `0${dt.getDay()}`.substr(-2);
    const D = days[dt.getDay()].substr(-2);
    const l = days[dt.getDay()];
    const Y = dt.getFullYear();
    const y = `${dt.getHours()}`.substr(-2);
    const H = `0${dt.getHours()}`.substr(-2);
    const h = `0${(dt.getHours() > 12) ? dt.getHours() - 12 : dt.getHours()}`.substr(-2);
    const i = `0${dt.getMinutes()}`.substr(-2);
    const s = `0${dt.getSeconds()}`.substr(-2);
    const vars = ['F', 'M', 'j', 'd', 'D', 'l', 'Y', 'y', 'H', 'h', 'i', 's']
    const formats = vars.forEach(e => {
        format = format.replace(eval('/' + e + '/gi'), (x) => {
            return (eval(x));
        })
        return format;
    })
    return format;
}

Comments

0
$newticket['DateCreated'] = date('d-m-Y G:H', strtotime($phpDateVariable));

2 Comments

the $phpDateVariable is already in the format you state above. I need to put into javascript format which is Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time)
Are you just asking for how to format a date in PHP? Go look at the formatting options in the documentation: us.php.net/manual/en/function.date.php
0

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.

Comments

0
 var phpTimeStamp = '2022-03-20 12:20:20'; /* timestamp format*/

 var jsDateObject = new Date(Date.parse( phpTimeStamp ));

Now you can access all property of a date object like

 jsDateObject.getHours(); //  gives hour 

And other functions as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.