surferpup

Minecraft Real World Time API

Feb 1st, 2014
2,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.24 KB | None | 0 0
  1. --[[
  2.    
  3.     Minecraft Real World Time API Version 1.0
  4.       by surferpup
  5.      
  6.     Allows for obtaining real world date/time variables
  7.     from www.timeapi.org.
  8.  
  9.     Numerous time date formats are pre-defined.  You can also return
  10.     all time elements as a table.
  11.    
  12.     A time out feature exists to return an error value if the website
  13.     times out.
  14.    
  15. ]]
  16.  
  17. local beforeString = "+hours+before+now"
  18. local afterString = "+hours+after+now"
  19. local now = "now"
  20. local timeZone = "edt"
  21. local modifier = 0
  22. local url="http://www.timeapi.org/"
  23. local httpString =""
  24. local requestTimeOut = 5
  25. local timeResult
  26.  
  27. --[[
  28.     These are the allowed parameters for formatting on timeapi.org
  29.    
  30.     In the url, the '%' character is substituted as % and the space is %20
  31.    
  32.     %a - The abbreviated weekday name (“Sun”)
  33.     %A - The full weekday name (“Sunday”)
  34.     %b - The abbreviated month name (“Jan”)
  35.     %B - The full month name (“January”)
  36.     %c - The preferred local date and time representation
  37.     %d - Day of the month (01..31)
  38.     %H - Hour of the day, 24-hour clock (00..23)
  39.     %I - Hour of the day, 12-hour clock (01..12)
  40.     %j - Day of the year (001..366)
  41.     %m - Month of the year (01..12)
  42.     %M - Minute of the hour (00..59)
  43.     %p - Meridian indicator (“AM” or “PM”)
  44.     %S - Second of the minute (00..60)
  45.     %U - Week number of the current year,
  46.          starting with the first Sunday as the first day
  47.          of the first week (00..53)
  48.     %W - Week number of the current year,
  49.          starting with the first Monday as the first day
  50.          of the first week (00..53)
  51.     %w - Day of the week (Sunday is 0, 0..6)
  52.     %x - Preferred representation for the date alone, no time
  53.     %X - Preferred representation for the time alone, no date
  54.     %y - Year without a century (00..99)
  55.     %Y - Year with century
  56.     %Z - Time zone name
  57.     %% - Literal “%” character
  58.    
  59. ]]
  60.  
  61. format={
  62.     timeShort_12 = 1;
  63.     timeLong_12 = 2;
  64.  
  65.     timeShort_24 = 3;
  66.     timeLong_24 = 4;
  67.  
  68.     dateShort = 5;
  69.     dateLong = 6;
  70.  
  71.     date_mmddyy= 5;
  72.     date_mmddyyyy = 6;
  73.  
  74.     date_ddmmyy = 7;
  75.     date_ddmmyyyy = 8;
  76.  
  77.     date_yymmdd =9;
  78.     date_yyyymmdd = 10;
  79.    
  80.     dateTime12_mmddyy = 11;
  81.     dateTime12_mmddyyyy = 12;
  82.     dateTime12_ddmmyy = 13;
  83.     dateTime12_ddmmyyyy = 14;
  84.    
  85.     dateTime24_mmddyy = 15;
  86.     dateTime24_mmddyyyy = 16;
  87.     dateTime24_ddmmyy = 17;
  88.     dateTime24_ddmmyyyy = 18;
  89.    
  90.     default=12;
  91.     defaultDate=6;
  92.     defaultTime=1;
  93.     raw = 19;
  94. }
  95.  
  96. dateSeparator=
  97. {
  98.     comma=",";
  99.     dash="-";
  100.     period=".";
  101.     slash="/";
  102.     underscore="_";
  103.     none="";
  104.    
  105. }
  106.  
  107. local separator= separator or dateSeparator.dash
  108.  
  109. formats ={
  110.     [1]="%l:%M %p";
  111.     [2]="%l:%M:%S %p";
  112.     [3]="%H:%M";
  113.     [4]="%l:5M:%S";
  114.    
  115.     [5]=("%m"..separator.."%d"..separator.."%y");
  116.     [6]=("%m"..separator.."%d"..separator.."%Y");
  117.    
  118.     [7]=("%d"..separator.."%m"..separator.."%y");
  119.     [8]=("%d"..separator.."%m"..separator.."%Y");
  120.    
  121.     [9]=("%y"..separator.."%m"..separator.."%d");
  122.     [10]=("%Y"..separator.."%m"..separator.."%d");
  123.    
  124.     [11]=("%m"..separator.."%d"..separator.."%y  %l:%M %p");
  125.     [12]=("%m"..separator.."%d"..separator.."%Y  %l:%M %p");
  126.     [13]=("%d"..separator.."%m"..separator.."%y  %l:%M %p");
  127.     [14]=("%d"..separator.."%m"..separator.."%Y  %l:%M %p");
  128.    
  129.     [15]=("%m"..separator.."%d"..separator.."%y  %H:%M");
  130.     [16]=("%m"..separator.."%d"..separator.."%Y  %H:%M");
  131.     [17]=("%d"..separator.."%m"..separator.."%y  %H:%M");
  132.     [18]=("%d"..separator.."%m"..separator.."%Y  %H:%M");
  133.    
  134.     [19] = ("");
  135. }
  136.  
  137. zones={
  138.     utc={zone="utc", name = "Coordinated Universal Time"};
  139.     cst={zone = "cst", name = "Central Standard Time"};
  140.     cdt={zone = "cdt", name = "Central Daylight Time"};
  141.     est={zone = "est", name = "Eastern Standard Time"};
  142.     edt={zone = "edt", name = "Eastern Daylight Time"};
  143.     pst={zone = "pst", name = "Pacific Standard Time"};
  144.     pdt={zone = "pdt", name = "Pacific Daylight Time"};
  145.     mst={zone = "mst", name = "Mountain Standard Time"};
  146.     mdt={zone = "mdt", name = "Mountain Daylight Time"};
  147.    
  148. }
  149.  
  150. local timeTableIndex = {
  151.     [1] = "dayNameShort";
  152.     [2] = "dayNameLong";
  153.     [3] = "monthNameShort";
  154.     [4] = "monthNameLong";
  155.     [5] = "preferredLocalDateTime";
  156.     [6] = "day";
  157.     [7] = "hour12";
  158.     [8] = "hour24";
  159.     [9] = "dayOfYear";
  160.     [10] = "month";
  161.     [11] = "minute";
  162.     [12] = "meridian";
  163.     [13] = "meridianCaps";
  164.     [14] = "second";
  165.     [15] = "weekNumberSunday";
  166.     [16] = "weekNumberMonday";
  167.     [17] = "dayOfWeek";
  168.     [18] = "preferredDate";
  169.     [19] = "preferredTime";
  170.     [20] = "yearShort";
  171.     [21] = "year";
  172.     [22] = "zone";
  173.     [23] = "error"  
  174. }
  175.  
  176. local function resetFormats()
  177.     formats ={
  178.         [1]="%l:%M %p";
  179.         [2]="%l:%M:%S %p";
  180.         [3]="%H:%M";
  181.         [4]="%l:5M:%S";
  182.        
  183.         [5]=("%m"..separator.."%d"..separator.."%y");
  184.         [6]=("%m"..separator.."%d"..separator.."%Y");
  185.        
  186.         [7]=("%d"..separator.."%m"..separator.."%y");
  187.         [8]=("%d"..separator.."%m"..separator.."%Y");
  188.        
  189.         [9]=("%y"..separator.."%m"..separator.."%d");
  190.         [10]=("%Y"..separator.."%m"..separator.."%d");
  191.        
  192.         [11]=("%m"..separator.."%d"..separator.."%y  %l:%M %p");
  193.         [12]=("%m"..separator.."%d"..separator.."%Y  %l:%M %p");
  194.         [13]=("%d"..separator.."%m"..separator.."%y  %l:%M %p");
  195.         [14]=("%d"..separator.."%m"..separator.."%Y  %l:%M %p");
  196.        
  197.         [15]=("%m"..separator.."%d"..separator.."%y  %H:%M");
  198.         [16]=("%m"..separator.."%d"..separator.."%Y  %H:%M");
  199.         [17]=("%d"..separator.."%m"..separator.."%y  %H:%M");
  200.         [18]=("%d"..separator.."%m"..separator.."%Y  %H:%M");
  201.        
  202.         [19] = ("");
  203.     }
  204. end
  205.  
  206. function setSeparator( separatorString )
  207.     separator = dateSeparator[separatorString] or separatorString or dateSeperator.dash
  208.     resetFormats()
  209. end
  210.  
  211. function getSeperator()
  212.     return separator
  213. end
  214.  
  215. local function getZones()
  216.     return zones
  217. end
  218.  
  219.  
  220. local function getHelp()
  221.     return help
  222. end
  223.  
  224. local function printHelp()
  225. end
  226.  
  227. function string:split(pattern)
  228.     local fields = {}
  229.     local start = 1
  230.     self:gsub("()("..pattern..")",
  231.        function(c,d)
  232.           table.insert(fields,self:sub(start,c-1))
  233.           start = c + #d
  234.        end
  235.     )
  236.     table.insert(fields, self:sub(start))
  237.     return fields
  238. end
  239.  
  240. local function split(stringToSplit,pattern)
  241.     local fields = {}
  242.     local start = 1
  243.     string.gsub(stringToSplit,"()("..pattern..")",
  244.        function(c,d)
  245.           table.insert(fields,string.sub(stringToSplit,start,c-1))
  246.           start = c + #d
  247.        end
  248.     )
  249.     table.insert(fields, string.sub(stringToSplit,start))
  250.     return fields
  251. end
  252.  
  253. local function getRequest()
  254.     result,timeResult = pcall (function() return (http.get(httpString)).readAll() end)
  255.     if not result then
  256.         return "BadReq"
  257.     else
  258.         return timeResult
  259.     end
  260. end
  261.  
  262. local function initiateTimer()
  263.     sleep(requestTimeOut)
  264.     timeResult = "timeout"
  265.     return timeResult
  266. end
  267.  
  268. local function startRequest(request,timeOut)
  269.     requestTimeOut = tonumber(timeOut) or 0
  270.     if requestTimeOut <=0 then requestTimeOut = false end
  271.     request = request or ""
  272.     httpString = request
  273.     if not requestTimeOut then
  274.         return getRequest()
  275.     else
  276.         parallel.waitForAny(getRequest,initiateTimer)
  277.         return timeResult
  278.     end
  279. end
  280.    
  281.  
  282. --[[
  283.    
  284.     PUBLIC API FUNCTIONS
  285.    
  286.    
  287. ]]
  288.  
  289. --[[ getTime, printTime
  290.  
  291.     Arguments
  292.    
  293.     timeZone:
  294.             A legitimate timezone from the zones table.
  295.             If it is not specified or in error, UTC is chosen.
  296.             You can print the pre-defined zones using
  297.             the printZones() function.
  298.    
  299.     offset:
  300.             An integer argument (positive or negative) to use
  301.             To offset time by x hours. Ex.  -47 would give
  302.             time/date 47 hours before the present time.
  303.    
  304.     dateTimeFormat:
  305.             An integer value from the format enumerator.
  306.             If not specified or in error, will use the
  307.             preferred local date/time format specified by
  308.             timeapi.org.  You can print the pre-defined
  309.             formats using the printFormats() function.
  310.  
  311. ]]
  312. function getTime(timeZone,offset,dateTimeFormat,timeOut)
  313.     timeZone = timeZone or "utc"
  314.     offset = offset or 0
  315.     dateTimeFormat = dateTimeFormat or format.raw
  316.     timeOut = timeOut or 0
  317.     if type(timeOut) ~= "number" then timeOut = 0 end
  318.     if not formats[dateTimeFormat]
  319.         then dateTimeFormat = format.default
  320.     end
  321.     offset = tonumber(offset)
  322.     offset = offset or 0
  323.     local modifierString = afterString
  324.     if offset < 0 then modifierString = beforeString offset = math.abs(offset) end
  325.     if not zones[timeZone] then
  326.         timeZone = "utc"
  327.     end
  328.     local formatString = formats[dateTimeFormat]
  329.     if formatString ~= "" then
  330.         formatString = "?format=" .. textutils.urlEncode(formats[dateTimeFormat])
  331.     else
  332.         formatString = ""
  333.     end
  334.     return startRequest((url..timeZone.."/"..tostring(offset)..modifierString..formatString),timeOut)
  335. end
  336.  
  337.  
  338. function printTime( ... )
  339.     print (getTime( ... ))
  340. end
  341.  
  342. --[[ getTimeTable, printTimeTable
  343.  
  344.     The ability to get the full time table of the current
  345.     date time allows for infinite flexibility in programming
  346.     your own time formats.
  347.    
  348.     Arguments
  349.    
  350.     timeZone:
  351.             A legitimate timezone from the zones table.
  352.             If it is not specified or in error, UTC is chosen.
  353.             You can print the pre-defined zones using
  354.             the printZones() function.
  355.    
  356.     offset:
  357.             An integer argument (positive or negative) to use
  358.             To offset time by x hours. Ex.  -47 would give
  359.             time/date 47 hours before the present time.
  360.    
  361.     makeNumeric:
  362.             boolean true, false
  363.             true -- will convert leading-zero strings in
  364.                 the time table to numeric values.  For example,
  365.                 the string value for 3 minutes is "03."  As a
  366.                 numeric, it will become the number value 3.
  367.                 However, if the value must be a string ("Monday"),
  368.                 it will remain a string.
  369.             false or nil -- will leave all values as strings.
  370. ]]
  371.  
  372.  
  373. function getTimeTable(timeZone,offset,makeNumeric,timeOut) --returns table
  374.     -- check arguments
  375.     timeZone = timeZone or "utc"
  376.     offset = offset or 0
  377.     offset = tonumber(offset)
  378.     timeOut = timeOut or 0
  379.     if type(timeOut) ~= "number" then timeOut = 0 end
  380.     local modifierString = afterString
  381.     if offset < 0 then
  382.         modifierString = beforeString
  383.         offset = math.abs(offset)
  384.     end
  385.     if not zones[timeZone] then
  386.         timeZone = "utc"
  387.     end
  388.     -- Set up timeapi.org format string and get time
  389.     local tableFormat = "?format=%25a,%25A,%25b,%25B,%25c,%25d,%25I,%25H,%25j,%25m,%25M,%25P,%25p,%25S,%25U,%25W,%25w,%25x,%25X,%25y,%25Y,%25z"
  390.     local timeTableAsString = startRequest(url..timeZone.."/"..tostring(offset)..modifierString..tableFormat,timeOut)
  391.    
  392.     -- create timeTable from string
  393.     local timeTable ={}
  394.     local tempTable = split(timeTableAsString,",")
  395.     if #tempTable > 1 then
  396.         for i = 1,#tempTable do
  397.             timeTable[ timeTableIndex[i] ] =  tempTable[i]
  398.         end
  399.        
  400.         -- Instead of strings ("01") use numeric values ( 1 )
  401.         if makeNumeric then
  402.             timeTable.day = tonumber(timeTable.day)
  403.             timeTable.hour12 = tonumber(timeTable.hour12)
  404.             timeTable.hour24 = tonumber(timeTable.hour24)
  405.             timeTable.dayOfYear = tonumber(timeTable.dayOfYear)
  406.             timeTable.month = tonumber(timeTable.month)
  407.             timeTable.minute = tonumber(timeTable.minute)
  408.             timeTable.second = tonumber(timeTable.second)
  409.             timeTable.weekNumberSunday = tonumber(timeTable.weekNumberSunday)
  410.             timeTable.dayOfWeek = tonumber(timeTable.dayOfWeek)
  411.             timeTable.year = tonumber(timeTable.year)
  412.         end
  413.     else
  414.         timeTable.error = tempTable[1]
  415.     end
  416.     return timeTable
  417. end
  418.  
  419. -- Gets time, prints all values in timeTable
  420. function printTimeTable( ... )
  421.     local timeTable = getTimeTable( ...)
  422.     -- use monitor height to pause output
  423.     local width,height = term.getSize()
  424.     local currentRow = 1
  425.     local function pause()
  426.         term.setCursorPos(1,height)
  427.         term.write("... Press any key to continue ...")
  428.         os.pullEvent("key")
  429.         term.setCursorPos(1,height)
  430.         term.clearLine()
  431.         currentRow = 1
  432.     end
  433.     for i,v in ipairs(timeTableIndex) do
  434.         print (v..": "..tostring(timeTable[v]))
  435.         currentRow = currentRow+1
  436.         if currentRow > height - 1 then
  437.             pause()
  438.         end      
  439.     end
  440. end
  441.  
  442. --[[ printZones, printFormats
  443.  
  444.     Utility functions to print what zones
  445.     or formats are pre-defined.
  446.    
  447.     Arguments
  448.    
  449.     timeZone:
  450.             A legitimate timezone from the zones table.
  451.             If it is not specified or in error, UTC is chosen.
  452.             You can print the pre-defined zones using
  453.             the printZones() function.
  454.    
  455.     offset:
  456. ]]
  457.  
  458. function printZones()
  459.     local zoneKeys = {}
  460.     for n in pairs(zones) do table.insert(zoneKeys, n) end
  461.     table.sort(zoneKeys)
  462.     for i,k in ipairs(zoneKeys) do
  463.         print (k.." ("..zones[k].name..")")
  464.     end
  465. end
  466.  
  467. function printFormats()
  468.     local formatKeys = {}
  469.    
  470.     -- use monitor height to pause output
  471.     local width,height = term.getSize()
  472.     local currentRow = 1
  473.     local function pause()
  474.         term.setCursorPos(1,height)
  475.         term.write("... Press any key to continue ...")
  476.         os.pullEvent("key")
  477.         term.setCursorPos(1,height)
  478.         term.clearLine()
  479.         currentRow = 1
  480.     end
  481.    
  482.     for n in pairs(format) do table.insert(formatKeys, n) end
  483.     table.sort(formatKeys)
  484.    
  485.     for i,k in ipairs(formatKeys) do
  486.         print (k.." ("..format[k]..")")
  487.         currentRow = currentRow+1
  488.         if currentRow > height - 1 then
  489.             pause()
  490.         end    
  491.     end
  492. end
Advertisement
Add Comment
Please, Sign In to add comment