Domanda

Il mio obiettivo è convertire un timestamp da MySQL in un oggetto Date JavaScript in modo efficiente. Ecco il mio frammento attuale che converte il timestamp di MySQL in una data formattata in PHP:

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

Sto quindi usando questo valore $ date per un grafico usando l'API per grafici di Google che richiede JavaScript Date object:

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

Il problema è che l'oggetto JavaScript Date inizia l'indice del mese con 0, quindi l'output è sempre 1 mese in anticipo . Qual è il modo più efficace per affrontare questo problema?

Grazie in anticipo!

È stato utile?

Soluzione

Puoi fornire al costruttore Date una data nel formato mm / gg / aaaa o aaaa / mm / gg e la convertirà:

>>> 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)

Altri suggerimenti

Devi sottrarre manualmente quel 1 extra dal numero del mese, temo. L'oggetto JS Date è un casino.

Per ottenere una data nella Rappresentazione di stringhe di date compatibile con la Google Data Charts DataTable like

"Date(2015,0,31)" // note the quotes from the json string and the 0 for January

senza scorrere le righe della query in php, potresti avere il formato MySQL direttamente in questo modo:

<?php
$sql = "
    SELECT 
        CONCAT('Date(', YEAR(datefield), ',', (MONTH(datefield)-1), ',', DAY(datefield), ')') AS gChartDate, 
        valuefield
    FROM 
        table 
    ORDER BY
        datefield
";
$query = $pdo->query($sql);
$fetchAll = $query->fetchAll(PDO::FETCH_NUM); // fetch in not-associative array
array_unshift($fetchAll, [['type'=>'date', 'label'=>'date'], 'value']); // add title row
$json = json_encode($fetchAll, JSON_NUMERIC_CHECK);

quindi in javascript:

var data = google.visualization.arrayToDataTable(<?php echo($json) ?>);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top