# YAML and DateTime

**URL:** <https://www.ruby-forum.com/t/yaml-and-datetime/111068>\
**Category:** Ruby\
**Created:** [August 2, 2007, 11:05am UTC](https://www.ruby-forum.com/t/yaml-and-datetime/111068 "2007-08-02T11:05:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Paul\_McMahon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/e9bcb4/32.png) [@Paul\_McMahon](https://www.ruby-forum.com/u/Paul_McMahon)\
**Post date:** [August 2, 2007, 11:05am UTC](https://www.ruby-forum.com/t/yaml-and-datetime/111068/1 "2007-08-02T11:05:23Z")

</div>

It seems that cannot store instances of DateTime, but instead stores  
them  
as Time.

irb(main):001:0\> require “yaml”  
=\> true  
irb(main):003:0\> YAML.load(DateTime.now.to\_yaml).class  
=\> Time

This causes issues when you have a DateTime that is out of range of Time

irb(main):005:0\> date\_time = DateTime.new(2041,1,1)  
=\> #\<DateTime: 4933041/2,0,2299161\>  
irb(main):006:0\> YAML.load(date\_time.to\_yaml)  
ArgumentError: time out of range  
from /usr/local/lib/ruby/1.8/yaml.rb:133:in `utc' from /usr/local/lib/ruby/1.8/yaml.rb:133:in`node\_import’  
from /usr/local/lib/ruby/1.8/yaml.rb:133:in `load' from /usr/local/lib/ruby/1.8/yaml.rb:133:in`load’  
from (irb):6

Does anyone have a fix or workaround for this?

Thanks,

Paul McMahon

---

<div class="post-metadata">

**Author:** ![Paul\_McMahon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/e9bcb4/32.png) [@Paul\_McMahon](https://www.ruby-forum.com/u/Paul_McMahon)\
**Post date:** [April 13, 2010, 5:21pm UTC](https://www.ruby-forum.com/t/yaml-and-datetime/111068/2 "2010-04-13T17:21:15Z")

</div>

There’s a workarount you can do,  
in /usr/local/lib/ruby/1.8/yaml/rubytypes.rb you have this definition of  
#to\_yaml on Date class.

1 class Date  
2 yaml\_as “tag:yaml.org,2002:timestamp#ymd”  
3 def to\_yaml( opts = {} )  
4 YAML::quick\_emit( self, opts ) do |out|  
5 out.scalar( “tag:yaml.org,2002:timestamp”, self.to\_s, :plain )  
6 end  
7 end  
8 end

What I do in my Rails app is to overide this implementation,

1 class Date  
2 yaml\_as “tag:yaml.org,2002:timestamp#ymd”  
3 def to\_yaml( opts = {} )  
4 YAML::quick\_emit( self, opts ) do |out|  
5 out.scalar( “tag:yaml.org,2002:timestamp”, self.to\_s(:utc), :plain  
)  
6 end  
7 end  
8 end

“self.to\_s(:utc)” is the difference in line 5.It works for me.

I hope this help.  
Bye.  
Juan M…
