开发者

How do I convert a mySQL DATETIME type to a string for use in Javascript?

I want to display a DATETIME I get from a mySQL database as a String in Javascript.

I'm using PHP to put the DATETIME into a variable: $mydatetime.

It displays fine on the PHP page, but not in my javascript function.

<?php
    echo $mydatetime       --> 2010-04-19 13:00:00
    echo "<script language=javascript>myfunction($mydatetime);</script>";        
?>

Javascript

function myfunction(mydatetime) {
    alert(mydatetime);
}

This produces an error in my console: Uncaught SyntaxError: Unexpected number

I've tried many things to try to convert mydatetime to a string, but nothing seems to be working开发者_高级运维.

Any help is appreciated, thanks.


I don't know what format you need for your function - you don't specify. Chances are you just need to enclose the value in quotes:

echo "<script language=javascript>myfunction('$mydatetime');</script>";    

But the general way to convert dates from mySQL to something else in PHP is:

  1. Turn the date into a timestamp: $mytimestamp = strtotime($mydatetime); Strtotime can read a great number of time formats, DATETIME is among them. Manual on strtotime here

  2. Output the timestamp in any format you like: echo date("Y-m-d", $mytimestamp); Manual on date formatting options here


It's a string, so Javascript needs it in quotes:

<?php
    echo $mydatetime       --> 2010-04-19 13:00:00
    echo "<script language=javascript>myfunction('$mydatetime');</script>";        
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜