LoginSignup
2

More than 5 years have passed since last update.

RubyXLで日付をchange_contentsしても適用されない問題

Last updated at Posted at 2018-11-05

概要

RubyXLでCellをchange_contentsする際に、日付を入れても日付として認識されず、フォーマットが適用されない問題にぶち当たった。

cell.change_contents(Time.zone.now) # これだとダメ

原因

Time.zone.nowだとダメな理由はものすごいシンプルで、change_contentsの挙動がDateかDateTimeだと変わっているからだった。

lib/rubyXL/cell.rb
# File 'lib/rubyXL/cell.rb', line 231

def change_contents(data, formula=nil)
  validate_worksheet
  @datatype='str'
  if data.is_a?(Date) || data.is_a?(DateTime)
    data = @workbook.date_to_num(data)
  end
  if (data.is_a?Integer) || (data.is_a?Float)
    @datatype = ''
  end
  @value=data
  @formula=formula
end

ref) Method: RubyXL::Cell#change_contents

解決方法

Date.currentを使えば解決!

cell.change_contents(Time.zone.now) # これだとダメ
cell.change_contents(Date.current)  # これだと大丈夫

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2