【问题标题】:Converting String to Datetime Rails将字符串转换为日期时间 Rails
【发布时间】:2014-10-13 05:08:03
【问题描述】:

我正在使用 LazyHighCharts 并尝试将 json 数据转换为仅显示最近 24 小时,我在将日期和时间(“2014-06-16 16:00:00”)转换为毫秒时遇到了一些麻烦。

数据结构

{"status": "ok", "data": [{"2014-06-16 16:00:00": 24.2},{"2014-06-17 12:00:00": 30.2},{"2014-06-18 17:00:00": 42.9}]} etc

控制器

@data = JSON.parse(open(@temperature.url).read)

dates = []
temps = []

@data['data'].each do |data|
 dates << data.keys
 temps << data.values
end 

datetime = dates.each do |d| DateTime.parse(d).to_i end

@graph = LazyHighCharts::HighChart.new('graph') do |f|
 f.chart(:height => '400')
 f.yAxis [:title => {:text => "Temperature", :margin => 20, style: { color: '#333'}}]
 f.series(:pointInterval => 1.hour, :pointStart => 30.day.ago, :type => 'area', :name => '24hrs', :data => [[datetime, temps]])
 f.options[:xAxis] = { :minTickInterval => 24 * 3600 * 1000, :type => "datetime", :dateTimeLabelFormats => { day: "%b %e"}, :title => { :text => nil }, :labels => { :enabled => true } }
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 highcharts


    【解决方案1】:

    您需要将字符串转换为 dateTime 作为第一个, 使用此代码:

    DateTime.parse("2011-05-19 10:30:14").strftime('%Q')
    

    或者这个代码:

    "2014-06-16 16:00:00".to_datetime.strftime('%Q')
    

    因此,您可以将日期字符串数组转换如下:

    dates.map!{|d| d.to_datetime.strftime('%Q')}
    

    帮助链接:link-1link-2

    【讨论】:

    • 谢谢大家,我了解这种格式,但不确定如何使用 json 中的 data.keys 实现它?说 'dates.to_datetime.strftime('%Q')' 给我 'undefined method `to_datetime' for #<0x007fef71dd39d0>
    【解决方案2】:

    在 Rails 中,您可以将格式正确的字符串转换为毫秒:

    "2014-06-16 16:00:00".to_datetime.strftime('%Q')
    

    【讨论】:

      【解决方案3】:

      您可以使用 Activesupport String#in_time_zone

      in_time_zone(zone = ::Time.zone)Link 将字符串转换为 TimeWithZone 如果设置了 Time.zone 或 Time.zone_default,则在当前区域中, 否则通过 String#to_time 将字符串转换为时间

      【讨论】:

        猜你喜欢
        • 2015-09-17
        • 1970-01-01
        • 2022-08-18
        • 2017-08-31
        相关资源
        最近更新 更多