JavaScript Date 对象的月份索引从 0 开始

我的目标是以有效的方式将 MySQL 中的时间戳转换为 JavaScript Date 对象.这是我当前的片段,它将 MySQL 时间戳转换为 PHP 中的格式化日期:

My goal is to convert a timestamp from MySQL into a JavaScript Date object in an efficient manner. Here is my current snippet that converts the MySQL timestamp into a formatted date in PHP:

<?php
// formats timestamp into following format: 2009, 7, 30
$date =  date("Y, n, j", strtotime($row["date"]));
?>

然后我将这个 $date 值用于使用需要 JavaScript Date 对象的 Google 图表 API 的图表:

I am then using this $date value for a chart using Google's charting API which requires JavaScript Date object:

data.setValue(<?=$count;?>, 0, new Date(<?=$date;?>));

问题在于 JavaScript Date 对象以 0 开始月份索引,因此输出总是提前 1 个月.处理这个问题最有效的方法是什么?

The problem is that the JavaScript Date object begins the month index with 0 so the output is always 1 month in advance. What is the most efficient way in dealing with this issue?

提前致谢!

推荐答案

您可以为 Date 构造函数提供一个 mm/dd/yyyy 或 yyyy/mm/dd 格式的日期,它会转换它:

You can feed the Date constructor a date in mm/dd/yyyy or yyyy/mm/dd format and it will convert it:

>>> new Date('7/30/2009');
Thu Jul 30 2009 00:00:00 GMT-0700 (Pacific Daylight Time)
>>> new Date('2009/7/30');
Thu Jul 30 2009 00:00:00 GMT-0700 (Pacific Daylight Time)

相关文章