简体   繁体   English

如何将mySQL DATETIME类型转换为在Javascript中使用的字符串?

[英]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. 我想显示从mySQL数据库获取的DATETIME,作为Javascript中的String。

I'm using PHP to put the DATETIME into a variable: $mydatetime. 我正在使用PHP将DATETIME放入变量:$ mydatetime。

It displays fine on the PHP page, but not in my javascript function. 它在PHP页面上显示正常,但在我的javascript函数中却显示不正常。

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

Javascript Java脚本

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

This produces an error in my console: Uncaught SyntaxError: Unexpected number 这在我的控制台中产生一个错误: 未捕获的SyntaxError:意外的数字

I've tried many things to try to convert mydatetime to a string, but nothing seems to be working. 我尝试了许多尝试将mydatetime转换为字符串的方法,但是似乎没有任何效果。

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: 但是将日期从mySQL转换为PHP中其他内容的一般方法是:

  1. Turn the date into a timestamp: $mytimestamp = strtotime($mydatetime); 将日期转换为时间戳: $mytimestamp = strtotime($mydatetime); Strtotime can read a great number of time formats, DATETIME is among them. Strtotime可以读取很多时间格式,其中DATETIME就在其中。 Manual on strtotime here 这里的 strtotime手册

  2. Output the timestamp in any format you like: echo date("Ymd", $mytimestamp); 以您喜欢的任何格式输出时间戳: echo date("Ymd", $mytimestamp); Manual on date formatting options here 手册上date格式选项这里

It's a string, so Javascript needs it in quotes: 这是一个字符串,因此Javascript需要用引号引起来:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM