lua-users home
lua-l archive

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

On Tue, Jun 10, 2014 at 2:11 PM, Levente Kovacs <> wrote:

> 2. Can I access unix time in Lua? Can I use the same functions like
> gettimeofday(), localtime_r() calls? Or does it have different calls for
> time?

If you are starting down the path of working with dates and times in
Lua, you may find my attached collection of date/time resources that I
put together for scripting NoteCase Pro helpful.

Best regards,


[Notice not included in the above original message:  The U.S. National
Security Agency neither confirms nor denies that it intercepted this
Title: Lua Date-Time Resources

Lua Date-Time Resources

This branch includes resources for scripts that handle dates and times.

See also in the Help file scriptable program commands that can also handle dates and times under the Date Property Commands and Custom Property Commands topics.

Table of contents

Date/Time-Related Specifications

Specs that share ISO 8601 formatting in common.

CalDAV RFC 4791

The CalDAV specification was first published in 2003 as an Internet Draft submitted to the Internet Engineering Task Force (IETF). In March 2007, the CalDAV specification was described in the RFC 4791CalDAV is designed for implementation by any collaborative software, client or server, that needs to maintain, access or share collections of events. It is developed as an open standard to foster interoperability between software from different implementers.
The architecture of CalDAV (partially inherited from the underlying specifications) organizes the data (events, tasks, free-busy info, notes) in directories (collections), where multiple items (resources) reside. The resources and collections can be accessed by one or more users, using standard HTTP and DAV semantics to detect conflicting changes, or to provide locking.

For access control the concept of ACLs are used, so each operation (view, edit, delete etc.) can be denied or granted per user. Therefore the specification requires that CalDAV servers must support "WebDAV Access Control Protocol" (RFC 3744). The calendar resources must use iCalendar format, which allows the server to understand and process the data. Parsing the iCalendar items is necessary, because the server has to support a number of calendaring-specific operations such as doing free-busy time reports and expansion of recurring events. With this functionality, a user may synchronize his or her own calendar to a CalDAV server, and share it among multiple devices or with other users. The protocol also supports non-personal calendars, such as calendars for sites or organizations.

Pasted from <>

Calendar Reference

The Calendar FAQ,

The Calendar Zone,

Calendar Reform,

Marcus Kuhn, A Summary of International Date and time notation,

Content Management Interoperability Services

Content Management Interoperability Services,

A recent standard from OASIS that has an incredible amount of adoption already, designed originally for interoperability between Enterprise Content Management (ECM) systems. CMIS treats data as objects and brokers the exchange of the objects between systems. I.e., one ECM system could be using iCalendar and another a different specification for tasks, calendar entries, and journal entries, but the two systems could still interoperate if using CMIS as the brokering layer.

Handles far more than the iCalendar data set.


GroupDAV is a computer protocol used to connect Open Source groupware clients with Open Source groupware servers. It is a lightweight protocol whose primary design goal is to be as simple as possible to implement, focusing more on real world issues with open source applications than on an extremely extensive command set. It is based on a subset of WebDAV.


hCalendar seems the best method I've hit so far for marking up iCalendar entries in HTML, including date/times. The result will display in web pages.

 hCalendar is a simple, open, distributed calendaring and events format, using a 1:1 representation of standard iCalendar (RFC2445) VEVENT properties and values in semantic HTML or XHTML. hCalendar is one of several open microformat standards suitable for embedding in HTML, XHTML, Atom, RSS, and arbitrary XML.

Want to get started with writing an hCalendar event? Use the hCalendar creator to write up an event and publish it, or follow the hCalendar authoring tips to add hCalendar markup to your page of upcoming events or events you mention in blog posts, wikis, etc.


The iCalendar standard (RFC2445), has been broadly interoperably implemented (e.g. Apple's "iCal" application built into MacOSX).

In addition, bloggers often discuss events on their blogs -- upcoming events, writeups of past events, etc. With just a tad bit of structure, bloggers can discuss events in their blog(s) in such a way that spiders and other aggregators can retrieve such events, automatically convert them to iCalendar, and use them in any iCalendar application or service.

This specification introduces the hCalendar format, which is a 1:1 representation of the aforementioned iCalendar standard, in semantic HTML. Bloggers can both embed hCalendar events directly in their web pages, and style them with CSS to make them appear as desired. In addition, hCalendar enables applications to retrieve information about such events directly from web pages without having to reference a separate file.

Pasted from <>

Wikipedia page, (overview, links to related resources).

iCalendar RFC 2445; see also Wikipedia page, (overview, links to related resources).

Note that iCalendar RFC 5545 WebCal obsoleted RFC 2445 iCalendar in September of 2009.

This MIME media type provides a standard content type for capturing calendar event, to-do and journal entry information. It also can be used to convey free/busy time information. The content type is suitable as a MIME message entity that can be transferred over MIME based email systems, using HTTP or some other Internet transport. In addition, the content type is useful as an object for interactions between desktop applications using the operating system clipboard, drag/drop or file systems capabilities.

This memo is based on the earlier work of the vCalendar specification for the exchange of personal calendaring and scheduling information. In order to avoid confusion with this referenced work, this memo is to be known as the iCalendar specification.

See also Content Management Interoperability Services.

iCalendar RFC 5545

Supercedes iCalendar RFC 2445, adds interoperability extensions.

This memo is intended to progress the level of interoperability possible between dissimilar calendaring and scheduling applications. This memo defines a MIME content type for exchanging electronic calendaring and scheduling information. The Internet Calendaring and Scheduling Core Object Specification, or iCalendar, allows for the capture and exchange of information normally stored within a calendaring and scheduling application; such as a Personal Information Manager (PIM) or a Group-Scheduling product.

The iCalendar format is suitable as an exchange format between applications or systems. The format is defined in terms of a MIME content type. This will enable the object to be exchanged using several transports, including but not limited to SMTP, HTTP, a file system, desktop interactive protocols such as the use of a memory- based clipboard or drag/drop interactions, point-to-point asynchronous communication, wired-network transport, or some form of unwired transport such as infrared.

The memo also provides for the definition of iCalendar object methods that will map this content type to a set of messages for supporting calendaring and scheduling operations such as requesting, replying to, modifying, and canceling meetings or appointments, to-dos, and journal entries. The iCalendar object methods can be used to define other calendaring and scheduling operations such as requesting for and replying with free/busy time data. Such a scheduling protocol is defined in the iCalendar Transport-independent Interoperability Protocol (iTIP) defined in [2446bis].

The memo also includes a formal grammar for the content type based on the Internet ABNF defined in [RFC5234]. This ABNF is required for the implementation of parsers and to serve as the definitive reference when ambiguities or questions arise in interpreting the descriptive prose definition of the memo. Additional restrictions that could not easily be expressed with the ABNF syntax are specified as comments in the ABNF. Comments with normative statements should be treated as such.

See also Content Management Interoperability Services.

ISO 8601

ISO 8601 itself apparently is not available as a free specification. (130 Swiss Francs).

This description of it looks like it might be the functional equivalent.

The Mathematics of the ISO 8601 Calendar, Useful information on the math underlying ISO 8601.

ISO 8601 Date and Time - Converting and implementing. Metalink collection plus snippets for conversion and implementation of ISO 8601. Includes algorithms for a variety of non-Lua programming languages (including C/‍​​C‍+) that might provide insights for Lua scripting.

ISO 8601 representation using the yyyy-MM-dd'T'HH:mm:ss.SSSZZ format, e.g. "2010-10-14T19:01:24.944+00:00".

Lua Date/Time Methods

Lua methods for date/time handling.

Calculating Day of Week

From the Lua-L listserv:

> My API delivers dates in the form yyyy-mm-dd but my design team wants DDD dd (i.e. Tue 14).

local y,m,d=stamp:match("(%d+)%-(%d+)%-(%d+)")
local t={year=y, month=m, day=d}
print("%a %d",os.time(t)))


You can do it with Lua's and os.time but this is more fun:

local int = math.floor

-- turn a Gregorian date into an RD number
-- as defined in Calendrical Calculations
-- Mon 0001-01-01 is RD 1
-- Wed 1858-11-17 is RD 678576 and MJD 0
-- Thu 1970-01-01 is RD 719163
function rd(y,m,d)
       if m > 2
       then m = m + 1
       else m = m + 13; y = y - 1
       return int(y*1461/4) - int(y/100) + int(y/400)
            + int(m*153/5) + d - 428

local days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }
function dow(rd)
       return days[rd % 7 + 1]

Date and Time Lua Library

Date and Time library for Lua 5.x, public domain, (Another page says about this library: "Pure Lua Date & Time module for Lua 5.x featuring date and Time string parsing, time addition & subtraction, time span calculation, support for ISO 8601 Dates, local time support, strftime-like formatting.")

Site says it's for use in a console. But platform agnostic.

Day Of Week And Days In Month Example

"The following code provides date functions that include calculating the number of days in a given month and the day of week for a given calendar day."

Display Calendar In Html

Displays a Calendar in HTML


LuaDate is a Lua module for date and time calculation and retrieval using the Gregorian Date system. This fork updates
a library by Jas Latrix for Lua 5.2 support.


LuaDate v2

Lua Date and Time module for Lua 5.x.

 * Date and Time string parsing.
 * Time addition and subtraction.
 * Time span calculation.
 * Support ISO 8601 Dates.
 * Local time support.
 * Lua module (not binary).
 * Formats Date and Time like strftime.

Pasted from:


Lua-Time library, Basic date/time functions for Lua, with millisecond precision.


This is a lua library for time and date manipulation.

Importantly, it allows you to convert time between locations (time zones).

Measuring Execution Time

With Lua, you can measure the execution time for a script or a script chunk by using the Lua os.clock function. That function returns an approximation of the operating system's current time in seconds (including decimal fractions of a second.)

The trick is to get the time at the beginning of the chunk or script, getting it again at the end of the script or chunk, then subtracting to get the elapsed time.

Note that you can isolate a portion of your code that is slowing things down by repeating such lines before and after different portions of your code.

Example Code:

  nClock = os.clock()

  -- do some scripted action here


You can also repeat actions to accumulate enough results to exaggerate differences so you can tell which of multiple methods are the fastest where the differences are too tiny to be discerned by a single execution of each method.

For example, the following script informs us that a particular unanchored pattern with capture search of a string 999,999 times is about 22 times slower than the same search and capture if the pattern is anchored to the beginning of the searched string (discontinue searching the string after you find the first match).

  s = "the quick brown fox jumps over the lazy dog"
  w = "foo"

  strPat = ".*()"..w
  nClock = os.clock()
  for i=1,999999 do s:find(strPat) end

  strPat = "^.*()"..w
  nClock = os.clock()
  for i = 1,999999 do s:find(strPat) end


Rosetta Code Lua Snippets

Category: Lua, at Includes links to snippets for date handling:

 Date format
 Date manipulation
 Day of the week
 Leap year

There may be others on that site that weren't categorized properly.

Sleeping Scripts

Clean sleep method using a repeat … until loop, by Peter Odding,

function wait(seconds)
  local start = os.time()
  repeat until os.time() > start + seconds

for i=1,10 do

See also large page of methods at

Daniel Hertrich's method:

I implemented a relatively simple way to wait for the reply, using a
custom timeout (set to 5 seconds here):

- send HTTP request
strQuery =  "GET " .. strVersionUrlUri .. " HTTP/1.1\r\nHost: " ..
strVersionUrlHost .. "\r\n\r\n"
   net.write(nSocket, strQuery)
     t1 = os.time()
       -- read HTTP response
       strReply = ""
       bFirstRead = true
       nTimeoutSec = 5

         if bFirstRead == true then
           repeat nSize, strChunk =
              until strChunk ~= "" or os.difftime(os.time(), t1) > nTimeoutSec
           nSize, strChunk =
          strReply = strReply .. strChunk
         bFirstRead = false
       until nSize <= 0

Suspending/Resuming a Script

Suspend/resume a Lua script using coroutines:

Time Zone Manipulation

Time Zone, Lua function that portably returns a timezone string in the form +hhmm or -hhmm,

luatz, a lua library for time and date manipulation, allowing conversion of time between time zones.

Unit Conversion Function

"This code provides a convert_to function that converts between any two units on a scale defined in a table in pairs of {name, equivalent number of previous unit}. The example given is time, but it can be adapted for Imperial units, military divisions, pre-decimalisation British pounds, or any other incremental system of measurement."

Tested with NoteCase Pro. Works well. -- PEM