Blankman
Blankman

Reputation: 266988

What is this Ruby function doing?

I am confused on how this returns:

def utc2user(t)
  ENV["TZ"] = current_user.time_zone_name 
  res = t.getlocal 
  ENV["TZ"] = "UTC"
  res
end

It first sets the ENV variable, then sets 'res' to the local value, then re-assignes ENV variable, then returns res?

Not sure I understand how this is convering from UTC to the user time zone?

Upvotes: 6

Views: 162

Answers (4)

glenn mcdonald
glenn mcdonald

Reputation: 15488

The getlocal method uses ENV["TZ"], so this is just a little dance to temporarily set it, use it, and then put it back.

Although in this case it's being put "back" to "UTC", not what it was before, which seems a little dubious. And there's an in_time_zone method for doing this directly, anyway!

Upvotes: 4

Raghu
Raghu

Reputation: 2563

This function takes the time as the input, it passes the users timezone to the TZ so that when the getlocal method is called it actually gets the time based on the user local timezone andnot on UTC. It then reverts back the TZ envt variable back to UTC and actually returns the users local time zone in the last line.

Upvotes: 2

Jacob Relkin
Jacob Relkin

Reputation: 163238

It returns the time according to the time zone name specified by current_user.time_zone_name by invoking getlocal on the passed-in Time object.

It then resets the current time zone to UTC and returns the Time object returned from getlocal at the time of that invocation (i.e. when the environment's time zone was whatever the user's time zone is).

Upvotes: 2

Chuck Callebs
Chuck Callebs

Reputation: 16441

The first line is setting the environmental time zone variable to the user's time zone in order to get the res value in the correct time for that user. If it didn't set it to the user's, the time would still be in UTC.

It then sets the environmental variable back to UTC time, which I assume is the application's default.

It then returns res.

Upvotes: 7

Related Questions