lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>> Is there anyway to generate the current date and current time given the
>> time zone?

Below is a slightly modified version of a function that I've been
using for generating time stamps in different time zones.

-----------------------------------------------------------------------------
-- Converts a time stamp (like the one returned by os.time()
-- into the requested format.  User some code
-- from http://lua-users.org/wiki/TimeZone)
--
-- @param timestamp      timestamp (string)
-- @param format         Lua time format (string)
-- @param tzoffset       time zone offset as "+hh:mm" or "-hh:mm"
--                        (ISO 8601) or "local" [string, optional, defaults
--                        to "local"]
-- @param tzname         name/description of the time zone [string, optional,
--                        defaults to tzoffset, valid XHTML is ok]
-- @return               formatted time (string)
-----------------------------------------------------------------------------
function format_time(timestamp, format, tzoffset, tzname)
   if tzoffset == "local" then  -- calculate local time zone (for the server)
      local now = os.time()
      local local_t = os.date("*t", now)
      local utc_t = os.date("!*t", now)
      local delta = (local_t.hour - utc_t.hour)*60 + (local_t.min - utc_t.min)
      local h, m = math.modf( delta / 60)
      tzoffset = string.format("%+.4d", 100 * h + 60 * m)
   end
   tzoffset = tzoffset or "GMT"
   format = format:gsub("%%z", tzname or tzoffset)
   if tzoffset == "GMT" then
      tzoffset = "+0000"
   end
   tzoffset = tzoffset:gsub(":", "")

   local sign = 1
   if tzoffset:sub(1,1) == "-" then
      sign = -1
      tzoffset = tzoffset:sub(2)
   elseif tzoffset:sub(1,1) == "+" then
      tzoffset = tzoffset:sub(2)
   end
   tzoffset = sign * (tonumber(tzoffset:sub(1,2))*60 +
tonumber(tzoffset:sub(3,4)))*60
   return os.date(format, timestamp + tzoffset)
end

Here are a few examples of usage:

> return format_time(os.time(), "!%H:%M:%S %z", "local")
03:26:36 -0700
> return format_time(os.time(), "!%H:%M:%S %z", "local", "PST")
03:26:40 PST
> return format_time(os.time(), "!%H:%M:%S %z", "-04:00", "EST")
06:26:48 EST
> return format_time(os.time(), "!%H:%M:%S %z", "-03:00", "(Rio de Janeiro)")
07:26:54 (Rio de Janeiro)
> return format_time(os.time(), "!%H:%M:%S %z", "-03:00", "BRT")
07:27:05 BRT
> return format_time(os.time(), "!%H:%M:%S %z", "-03:00")
07:27:22 -03:00
> return format_time(os.time(), "!%H:%M:%S %z", "GMT")
10:27:26 GMT

- yuri

-- 
http://sputnik.freewisdom.org/