Skip to content

Instantly share code, notes, and snippets.

@rwjblue
Created May 19, 2011 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwjblue/981419 to your computer and use it in GitHub Desktop.
Save rwjblue/981419 to your computer and use it in GitHub Desktop.
Add Time.strptime
From 184e3de1046884dcf6467d19cf73a7eb65f811f5 Mon Sep 17 00:00:00 2001
From: Robert Jackson <robertj@promedicalinc.com>
Date: Thu, 19 May 2011 18:02:00 -0400
Subject: [PATCH 1/2] Add RubySpec for Time#strptime.
---
spec/ruby/library/time/strptime_spec.rb | 12 ++++++++++++
1 files changed, 12 insertions(+), 0 deletions(-)
create mode 100644 spec/ruby/library/time/strptime_spec.rb
diff --git a/spec/ruby/library/time/strptime_spec.rb b/spec/ruby/library/time/strptime_spec.rb
new file mode 100644
index 0000000..8051428
--- /dev/null
+++ b/spec/ruby/library/time/strptime_spec.rb
@@ -0,0 +1,12 @@
+require File.expand_path('../../../spec_helper', __FILE__)
+require 'time'
+require 'date'
+
+describe "Time.strptime" do
+ it "parses input strings in given format" do
+ today = Date.today
+ Time.utc(2001, 10, 14, 13, 25, 5).should == Time.strptime('2001-10-14 13:25:05 GMT', '%Y-%m-%d %H:%M:%S %Z')
+ Time.local(today.year, today.month, today.day, 13, 25, 5).should == Time.strptime('13:25:05', '%H:%M:%S')
+ Time.local(today.year, today.month, today.day, 13, 25, 0).should == Time.strptime('13:25', '%H:%M')
+ end
+end
--
1.7.4.4
From 25809f1a6c6628aba4b8f5902b14bb11041813db Mon Sep 17 00:00:00 2001
From: Robert Jackson <robertj@promedicalinc.com>
Date: Thu, 19 May 2011 18:02:21 -0400
Subject: [PATCH 2/2] Implement Time#strptime.
---
lib/time.rb | 15 +++++++++++++++
1 files changed, 15 insertions(+), 0 deletions(-)
diff --git a/lib/time.rb b/lib/time.rb
index 2fc4f5c..6dcfa2c 100644
--- a/lib/time.rb
+++ b/lib/time.rb
@@ -243,6 +243,21 @@ class Time
make_time(year, d.mon, d.mday, d.hour, d.min, d.sec, d.sec_fraction, d.zone, now)
end
+ #
+ # Parses +date+ using Date._strptime and converts it to a Time object.
+ #
+ # If a block is given, the year described in +date+ is converted by the
+ # block. For example:
+ #
+ # Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
+ def strptime(date, format, now=self.now)
+ d = Date._strptime(date, format)
+ raise ArgumentError, "invalid strptime format - `#{format}'" unless d
+ year = d[:year]
+ year = yield(year) if year && block_given?
+ make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
+ end
+
MonthValue = {
'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
--
1.7.4.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment