Button Button Button

Previous Next

I often find myself searching for the date formats I need for a call to os.date(). Finally I wrote a Lua script that does it for me by searching the output of all possible formats for the given keywords and printing all matching outputs.

Author: Peter Odding

License: MIT/X11 Tags: datetime locale

Snippet

#!/usr/bin/env lua

local function printf(s, ...)
  io.write(s:format(...), '\n')
end

if arg[1] == '-l' then
  table.remove(arg, 1)
  local locale = os.getenv 'LANG'
  if locale then os.setlocale(locale) end
end

local keyword = (arg[1] or ''):lower()
if keyword == '' then
  printf([[Usage: %s [-l] KEYWORD
Find the date format that results in KEYWORD for the current date. Use -l
to search localized os.date() outputs, this will call os.setlocale($LANG).
]], arg[0] or 'ldatefmt')
else
  local function scan(first, last)
    for i = first:byte(), last:byte() do
      local format = '%' .. string.char(i)
      local result = os.date(format)
      if result:lower():find(keyword) then
        printf('%q gives %q', format, result)
      end
    end
  end
  scan('A', 'Z')
  scan('a', 'z')
end

Tests/Usage

$ ldatefmt sat
"%A" gives "Saturday"
"%a" gives "Sat"
"%c" gives "Sat Jan  8 16:45:31 2011"

$ ldatefmt -l za
"%A" gives "zaterdag"
"%a" gives "za"
"%c" gives "za 08 jan 2011 16:46:04 CET"

Related Snippets


Revision 000003 by Peter Odding; created Sat, 08 Jan 2011 15:41:34 +0000

0 comments

Add a Comment