Add duration parsing to core.time?

Justin Whear justin at economicmodeling.com
Tue Aug 20 10:57:19 PDT 2013


While working on a configuration file parser, I found myself trying to 
decide which units to use for various time variables (e.g. 
`expireInterval`) which is silly because we have an excellent Duration 
structure in core.time.  I was pleased to discover that Duration has a 
toString method which prints a nice, human-readable description.  
Unfortunately, there appears to be no corresponding parse method.  Turns 
out that it's surprisingly easy to write thanks to the existing 
functionality in std.conv: http://dpaste.dzfl.pl/1500b834

It appears that DPaste stumbles over the unicode 'μs' in the units enum, 
so here's a test invocation and output:

$ dmd -unittest test_duration.d && ./test_duration '12 hours, 30 minutes' 
'1w2d20m12h5m2s'
12 hours and 30 minutes
1 week, 2 days, 12 hours, 25 minutes, and 2 secs

I've made the implementation more flexible than simply parsing the very 
standard output of Duration.toString by adding more unit synonyms and 
making whitespace, commas, and 'and' optional.  All this really requires 
is a sequence of digits followed by a unit name, possibly repeating;  
leading to the very compact form used in '1w2d20m12h5m2s'.
All validation is performed by the two calls to std.conv.parse, so 
invalid strings should fail (e.g. 'four madeupunits').

One possible improvement is to support written-out numbers such as 
"seven" and "forty-two", but I suspect this would entail a much more 
involved implementation.

Thoughts on including something like this core.time?  My thought is that 
Duration could have a `this(string)` with a non-consuming version of this 
function for automatic to! support in addition to providing parse.

Justin


More information about the Digitalmars-d mailing list