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?

axelmukwena
  • 779
  • 7
  • 24

1 Answers1

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.

eux
  • 3,072
  • 5
  • 14