0

I am trying to graph data that I am pulling from an ActiveRecord query in Ruby on Rails. The JavaScript charting library (amcharts) accepts data in the following form:

 var chartData = [{
            date: new Date(2012, 0, 1),
            products: 227
        }, {
            date: new Date(2012, 0, 2),
            products: 371
        }]

How do I parse a date string in the format YYYY-MM-DD and create a JavaScript Date object from the query below? I've seen this tutorial but I'm having trouble figuring out how to write a function to correctly parse the json output.

  create_table :products do |t|
        t.date :date
  end

 <% a = Product.select("date(date) as date, count(id) as products").group("date(date)").to_a.to_json %>
4
  • Are your sure it won't take YYYY-MM-DD dates? This suggests it will: blog.amcharts.com/2011/03/… Commented Jul 2, 2012 at 2:27
  • It seems like they are using function parseCSV(data) to parse the CSV column to a JavaScript date object. I guess my question is, how to a write a similar function to parse the json above?
    – diasks2
    Commented Jul 2, 2012 at 3:23
  • Have you looked at the next tutorial? " our data contains simple date strings, not Date Objects. Chart should get Date Objects in order to parse dates. We will continue this tutorial and will explain how to do all these things." Commented Jul 2, 2012 at 3:33
  • Yes, if we are talking about the same one, then I think it is the one I linked to in my question. I am still having trouble though. In that tutorial the parse function loops through the CSV file and parses the dates. I'm unsure of how to write a similar function to loop through this <% a = Product.select("date(date) as date, count(id) as products").group("date(date)").to_a.to_json %> to achieve the same result. Parsing a json array instead of a CSV file.
    – diasks2
    Commented Jul 2, 2012 at 3:49

1 Answer 1

0

Here is the answer that worked for me:

 function parseDate(dateString) {
     // split the string get each field
     var dateArray = dateString.split("-");
     // now lets create a new Date instance, using year, month and day as parameters
     // month count starts with 0, so we have to convert the month number
     var date = new Date(Number(dateArray[0]), Number(dateArray[1]) - 1, Number(dateArray[2]));
     return date;
 }

     var array = <%= a.to_json %>;

     var array2 = [];

     array.forEach(function(element){ 
       array2.push({date: parseDate(element.date), products: element.products});
     });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.