[英]How to convert MySQL Timestamp to Javascript date?
I want to display a Google Chart (Line Chart) on .jsp page of my Spring MVC application. 我想在Spring MVC应用程序的.jsp页面上显示Google图表(折线图)。 The data is retrieved from a MySQL database, so I need to convert the YYYY-MM-DD HH:MM:SS
format into Javascript's Date. 数据是从MySQL数据库检索的,因此我需要将YYYY-MM-DD HH:MM:SS
格式转换为Javascript的Date。
The database is created by Hibernate. 该数据库由Hibernate创建。 The Reading
entity has a time
field of type java.sql.Timestamp
, which is stored as DATETIME
in the database. Reading
实体具有一个类型为java.sql.Timestamp
的time
字段,该字段以DATETIME
java.sql.Timestamp
存储在数据库中。
The results
is an Iterable<Reading>
object passed to the .jsp via controller. results
是一个Iterable<Reading>
对象,该对象通过控制器传递给.jsp。 It is passed correctly (I am displaying the data as a table, too). 它已正确传递(我也将数据显示为表格)。
I'm trying to use the solution proposed here , but it does not work. 我正在尝试使用此处提出的解决方案,但是它不起作用。
Here's the code I'm trying to populate the chart with: 这是我尝试使用以下图表填充的代码:
<c:forEach items="${results}" var="reading">
var t = "${reading.time}".split(/[- :]/);
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.addRow([d,${reading.temperature}]);
</c:forEach>
The chart is not displaying. 图表未显示。
Facts: 事实:
java.sql.Timestamp
is a subclass of java.util.Date
. JDBC的java.sql.Timestamp
是java.util.Date
的子类。 <fmt:formatDate>
for converting java.util.Date
to String
. JSTL有一个<fmt:formatDate>
用于将java.util.Date
转换为String
。 Date
constructor can take ao a string in ISO8601 time format. JavaScript Date
构造函数可以采用ISO8601时间格式的字符串。 Put together: 放在一起:
<c:forEach items="${results}" var="reading">
<fmt:formatDate var="time" value="${reading.time}" pattern="yyyy-MM-dd'T'HH:mm:ss" timeZone="UTC" />
var d = new Date("${time}");
// ...
</c:forEach>
Alternatively, just convert results
to JSON using a decent JSON formatter in the controller and print it as if it's a JS variable like so var data = ${data};
或者,只需在控制器中使用适当的JSON格式器将results
转换为JSON,然后像打印JS变量一样将其打印出来,就像var data = ${data};
. 。 See also ao How to access array of user defined objects within <script> in JSP? 另请参见ao 如何在JSP中的<script>中访问用户定义对象的数组?
Unrelated to the concrete problem: make sure your model is of java.util.Date
type. 与具体问题无关 :确保模型为java.util.Date
类型。 You shouldn't have java.sql.*
typed properties in your model. 您的模型中不应包含java.sql.*
类型的属性。 If you're using plain JDBC, just upcast ResultSet#getTimestamp()
to java.util.Date
directly. 如果使用的是纯JDBC,则只需直接将ResultSet#getTimestamp()
上载到java.util.Date
。 See also ao Handling MySQL datetimes and timestamps in Java . 另请参见ao 在Java中处理MySQL日期时间和时间戳 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.