Skip to content

Commit

Permalink
Create time_converter.cr
Browse files Browse the repository at this point in the history
Adds time converter for parsing time strings
  • Loading branch information
eliasjpr committed Jun 1, 2023
1 parent 76e21fa commit cdd64f8
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/schema/ext/time/time_converter.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require "../../annotations"

@[Schema::Definition::Scalar]
struct Time
module TimeConverter
# Put *value* as a time timestamp into the *builder* at *key*.
def self.to_http_param(value : Time, builder : HTTP::Params::Builder, key : String)
builder.add(key, to_http_param(value))
end

# Return *value* as a time timestamp string.
def self.to_http_param(value : Time)
value.to_unix.to_s
end

# Parse `Time` from an HTTP param as time timestamp.
def self.from_http_param(value : String) : Time
Time.parse(value, "%Y-%m-%d %H:%M:%S %z", Time::Location::UTC)
rescue ArgumentError
raise TypeCastError.new
end
end
end

0 comments on commit cdd64f8

Please sign in to comment.