【问题标题】:Ruby / Rails / JavaScript / JSON - parsing and formatting datesRuby / Rails / JavaScript / JSON - 解析和格式化日期
【发布时间】:2012-07-02 01:13:16
【问题描述】:

我正在尝试绘制从 Ruby on Rails 中的 ActiveRecord 查询中提取的数据。 JavaScript 图表库 (amcharts) 接受以下形式的数据:

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

如何解析格式为 YYYY-MM-DD 的日期字符串并从下面的查询中创建 JavaScript Date 对象?我已经看到了这个tutorial,但我无法弄清楚如何编写一个函数来正确解析 json 输出。

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

【问题讨论】:

  • 您确定它不需要 YYYY-MM-DD 日期吗?这表明它将:blog.amcharts.com/2011/03/…
  • 似乎他们正在使用function parseCSV(data) 将 CSV 列解析为 JavaScript 日期对象。我想我的问题是,如何编写一个类似的函数来解析上面的 json?
  • 你看过next教程了吗? " 我们的数据包含简单的日期字符串,而不是日期对象。图表应该获取日期对象以解析日期。我们将继续本教程并解释如何做所有这些事情。"
  • 是的,如果我们谈论的是同一个,那么我认为这是我在问题中链接到的那个。我仍然有麻烦。在该教程中,解析函数循环遍历 CSV 文件并解析日期。我不确定如何编写一个类似的函数来循环这个&lt;% a = Product.select("date(date) as date, count(id) as products").group("date(date)").to_a.to_json %&gt; 以达到相同的结果。解析 json 数组而不是 CSV 文件。

标签: javascript ruby-on-rails ruby json


【解决方案1】:

这是对我有用的答案:

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

【讨论】:

    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 2014-11-10
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多