Monday, February 21, 2011

How to get local time zone name from Ruby in the same way as Java does?

I need to find out local machine time zone name from Ruby (from the TZInfo::Timezone.all_identifiers list of values). I need it so that I could set correctly Oracle database session time zone so that I could handle correctly timestamp with time zone values in the database.

I would like to get the same value that in Java you could get with java.util.TimeZone.getDefault().getID() (which on my computer returns "Europe/Riga"). As far as I have had a look on JDK sources there is platform specific C functions which finds this default time zone.

So when using JRuby then I can call this Java method. But I need a solution that I can use with MRI.

I tried to use Time.now.zone but it returns different results (in my case "EET" or "EEST") depending on if currently is daylight saving time or not. So I really would need to get in the previously mentioned location format (like "Europe/Riga") which correctly specifies dates when switching to daylight saving time happens.

Any suggestions?

From stackoverflow
  • JRuby returns EET/CDT-like values for compatibility reasons, since C-Ruby does the same. But, since JRuby can easily call the Java layer, you could just call it like tat:

    require 'java'
    id = java.util.TimeZone.getDefault().getID()
    

    or, in more Ruby-like syntax:

    require 'java'
    id = java.util.TimeZone.get_default.get_id
    

    Alternatively, you could use JodaTime:

    require 'java'
    id = org.joda.time.DateTimeZone.getDefault.getID
    
    Raimonds Simanovskis : Yes, in JRuby it's easy. But I would like to get the same result in MRI (original C based Ruby interpreter).
    VVSiz : I don't think MRI has a way to do that without some tricks or native calls. On Linux, it is easy, just "cat /etc/timezone".

0 comments:

Post a Comment