0

Here i want to get JavaScript date in google chart and am passing date as yyyy-mm-dd format and i want to convert it to JavaScript in order to produce the graph.here is the console what am passing to the google chart enter image description here

now i want to get the date in JavaScript type as new Date(2021,07,29) and new Date(2021,08,28)..i had gone through several ways but didn't get an solution.. Here is my google chart code

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
   var user =  {!! json_encode($user) !!};
   var user = JSON.parse(user);
   console.log(user);
    google.charts.load('current', {
        'packages': ['timeline']
    });
    google.charts.setOnLoadCallback(lineChart);
    function lineChart() {
    var data = google.visualization.arrayToDataTable(user);
    var options = {
            title: 'Wildlife Population',
            curveType: 'function',
            legend: {
                position: 'bottom'
            }
        }; 
    var chart = new google.visualization.Timeline(document.getElementById('monthly_report_timeline'));
    chart.draw(data, options);
    }        
</script>
user_777
  • 845
  • 1
  • 9
  • 25

1 Answers1

0

The question isn't clear. Presumably dates are being passed in the JSON as timestamps in YYYY-MM-DD HH:mm:ss format but you need them as Date objects. You can do that as part of JSON.parse using a reviver function.

Since the timestamps are not in a format supported by ECMA-262, you should parse them manually (also see Converting a string to a date in JavaScript, a library can help) rather than using the built–in parser, e.g.

// Parse date in YYYY-MM-DD HH:mm:ss format
function parseDate(date) {
  let [Y, M, D, H, m, s] = date.split(/\D/);
  return new Date(Y, M-1, D, H, m, s);
}

let jsonSource = '["Name","2021-07-29 00:00:00","2021-08-28 00:00:00"]';
let pattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/; 
let foo = JSON.parse(
  jsonSource, 
  (key, value) => pattern.test(value)? parseDate(value) : value
);

// Result
foo.forEach((value, i) => console.log(i + ' ' + typeof value + ' "' + value + '"'));
RobG
  • 142,382
  • 31
  • 172
  • 209