I have a date pulled from my mysql database in the form YYYY-MM-DD.
Now I have some javascript that requires the dates like this:
data: [
开发者_运维知识库 [Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
So I thought I could do the following:
while($row = mysql_fetch_array($sql)){
$thedate = explode('-', $row['date']); //$row['date'] = YYYY-MM-DD
$str .= '[Date.UTC(' . $thedate[0].','.$thedate[1].','.$thedate[2].'), '.$row['answer'].'],';
$i++;
}
And then simply capture this in the browser side using an AJAX request in a variable data
, giving:
data: [data]
When alerting the contents of data I notice I get something like the following for 22nd & 23rd August:
[Date.UTC(2011, 08, 22), 55], [Date.UTC(2011, 08, 23), 65]
When what I need is
[Date.UTC(2011, 7, 22), 55], [Date.UTC(2011, 7, 22), 65]
Can someone tell me how to convert convert the date pulled from the db relation into the correct format....
YYYY
Which format is that? Anyway, use DateTime::createFromFormat
to parse the date, after that you can format it anyway you like.
Example:
while($row = mysql_fetch_array($sql)){
$Date = DateTime::createFromFormat( 'Y-m-d', $row['date'] );
$str .= '[Date.UTC(' . $Date->format('Y') . ', ';
$str .= $Date->format('n') - 1 . ', ';
$str .= $Date->format('j') . '), ' . $row['answer'] . '],';
}
By the way, have a look at json_encode
http://php.net/manual/en/function.json-encode.php
while($row = mysql_fetch_array($sql)){
$timestamp = strtotime($row['date']);
$str .= '[Date.UTC(' . date('Y', $timestamp). ', ';
$str .= date('n', $timestamp) - 1 . ', ';
$str .= date('j', $timestamp) . '), ' . $row['answer'] . '],';
}
about DateTime - this is a great class but avaliable only for pphp >= 5.2
精彩评论