Time- and date-valued data offer a wide range of headaches for real-world data processing applications. Silex 0.0.4 introduces a very simple class to represent a timestamp in UTC, along with a flexible mechanism for converting instances of this class to other timestamp representations for further processing.
Here’s a simple example of it in action:
The idea is not that DateTimeUTC
is a reasonable general-purpose representation for timestamps (it is absolutely not). Rather, it is intended to:
- provide a straightforward intermediate format for time values that may be converted from one of several string formats to one of several richer date and time libraries,
- contain enough information to reconstruct a clock time (with optional millisecond accuracy) in a variety of preferred, richer representations,
- enable libraries that provide generic date processing without imposing a choice of a date and time library on client code, and
- provide a simple mechanism for inspecting components of time values.
Implementing conversions
In order to meet these requirements, Silex provides two interfaces involving DateTimeUTC
instances.
The first is the conversion interface, given by the as[T]
method in DateTimeUTC
and the from[T](T)
method in the companion object. In order to extend these for arbitrary T
, simply ensure that witness functions converting from T
to DateTimeUTC
(for from
) and from DateTimeUTC
to T
(for as
) are in scope. (Silex provides implementations of these for Joda-Time’s DateTime
class.)
The second interface is the TimeLens
trait, which lets applications define conversions from a particular string-based time format to a DateTimeUTC
instance and back. (This is not exactly a “lens” in the functional programming sense, since it doesn’t extract or modify individual components of the time, but it provides the round-trip functionality of a lens.) Silex currently includes one TimeLens
(to convert to and from timestamps in the format used by Amazon Web Services billing data); we’ve reproduced it below as an example:
(If you develop a useful TimeLens
, please contribute it as a pull request!)
Most data processing code will only need declare a custom TimeLens
and convert string timestamps to seconds since the UNIX epoch. However, since Silex lets users declare arbitrary round-trip conversions between string formats and DateTimeUTC
instances and between DateTimeUTC
instances and objects in any alternative date and time representation, it is possible to write more sophisticated time-processing code concisely and generically.