0

I am writing a custom DateTime method to get current web viewer's timezone and set all the time views to his/her timezone.

How I get local timezone

# index.html.erb

<%= get_time( getTimeZone(), entry.created_at) %>  # getTimeZone() => "Asia/Shanghai", wrong usecase
<%= get_time("Asia/Shanghai", entry.created_at) %>  # works like charm
 
<script>
     function getTimeZone() {
        return Intl.DateTimeFormat().resolvedOptions().timeZone
    }
</script>

Below I simply convert database UCT time to user local timezone, then calculate the ago time difference.

# application_helper.rb
def get_time(user_zone, created_at)
    user_now = Time.find_zone(user_zone).now
    created_at_local = created_at.in_time_zone(user_zone)

    difference = user_now - created_at_local
    if 60 > difference
      difference.round.to_s + "s"
    elsif 3600 > difference
      (difference / 1.minute).round.to_s + "m"
    elsif 86400 > difference
      (difference / 1.hour).round.to_s + "h"
    else
      created_at_local.strftime("%b %d, %Y")
    end
  end

How can I connect the two? Or maybe how can I implement the rails method in JS?


I just realized rails escape forward slashes?? I thought it was only peculiar in routes. I've tried all forms of substituting but non-works.

"Asia/Shanghai" => ""

Any displacements?

1 Answer 1

1

You could use JavaScript save TimeZone to cookies, then read cookies in Rails to get TimeZone. Example code

And there's a gem called Local Time you may want to check out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.