How do I find the current system timezone?

后端 未结 12 474
攒了一身酷
攒了一身酷 2020-11-30 06:22

On Linux, I need to find the currently configured timezone as an Olson location. I want my (C or C++) code to be portable to as many Linux systems as possible.

For e

12条回答
  •  广开言路
    2020-11-30 07:15

    I liked the post made by psmears and implemented this script to read the first output of the list. Of course there must have more elegant ways of doing this, but there you are...

        /**
         * Returns the (Linux) server default timezone abbreviation
         * To be used when no user is logged in (Ex.: batch job)
         * Tested on Fedora 12
         * 
         * @param void
         * @return String (Timezone abbreviation Ex.: 'America/Sao_Paulo')
         */
        public function getServerTimezone()
        {
    
            $shell = 'md5sum /etc/localtime';
            $q = shell_exec($shell);
            $shell = 'find /usr/share/zoneinfo -type f | xargs md5sum | grep ' . substr($q, 0, strpos($q, '/') - 2);
            $q = shell_exec($shell);
            $q = substr($q, strpos($q, 'info/') + 5, strpos($q, " "));
            return substr($q, 0, strpos($q, chr(10)));
    
        }
    

    In my Brazilian Fedora 12, it returns:
    Brazil/East

    And does exactly what I need.

    Thank you psmears

提交回复
热议问题