solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Default value for Time or DateTime attribute #257

Closed psulightning closed 10 years ago

psulightning commented 10 years ago

I have a class that uses attribute :start_date, Time, :default=>Proc.new{|str| Time.parse(str)}. I am receiving from a different system which sends me Date/Time information without timezone as a string. Using attribute :start_date, DateTime puts this attribute in UTC, but I want US Eastern Time. Using Time instead of DateTime offsets to Time.zone instead just appending the missing timezone information.

The question is: is there are way to have the default value be with the correct timezone?

Thank you.

dkubb commented 10 years ago

@psulightning Can you set the TZ environment variable to the timezone you want to use for the default?

If that's too "global" for your tastes, and you're using activesupport, you could use this:

TIME_ZONE = ActiveSupport::TimeZone['Eastern Time (US & Canada)']

# ...

attribute :start_date, Time, default: proc { |string| TIME_ZONE.parse(string) }

Since you mentioned Time.zone in your question I figured you may have AS available.

psulightning commented 10 years ago

Sorry, I should have mentioned that I am using Rails 4 and have config.time_zone = "Eastern Time (US & Canada)"

dkubb commented 10 years ago

@psulightning then Time.zone.parse(string) should just work. Time.zone returns your current configured timezone, and calling #parse on it will use that timezone for the default when none can be inferred from the string itself.

psulightning commented 10 years ago

I figured out that the problem was upstream. The string was formatted incorrect prior to getting to Virtus. But, I at least know how to do it in the future. Thank you.

dwhelan commented 9 years ago

:+1: