Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing date and time with FParsec
    text
    copied!<p>Within a simple query language I'd like to recognize date and time literals, preferably without using delimiters. For example,</p> <pre><code>CreationDate = 2013-05-13 5:30 PM </code></pre> <p>I could use a combinator to detect the basic syntax (e.g., <code>yyyy-MM-dd hh:mm tt</code>), but then it needs to be passed to <code>DateTime.TryParse</code> for full validation. </p> <p>A few questions:</p> <ul> <li>Is there a combinator for "post processing" a parser result, e.g., <code>pstring "1/2/2000" |&gt; (fun s -&gt; try OK(DateTime.Parse s) with _ -&gt; Fail("not a date"))</code></li> <li>Is it possible to apply a predicate to a string (as <code>satisfy</code> does to <code>char</code>)?</li> <li>Is there a better approach for parsing date/time?</li> </ul> <h3>UPDATE</h3> <p>Using Guvante's and Stephan's examples, I came up with this:</p> <pre><code>let dateTimeLiteral = let date sep = pipe5 pint32 sep pint32 sep pint32 (fun a _ b _ c -&gt; a, b, c) let time = (pint32 .&gt;&gt;. (skipChar ':' &gt;&gt;. pint32)) .&gt;&gt;. (opt (stringCIReturn " am" false &lt;|&gt; stringCIReturn " pm" true)) (date (pstring "/") &lt;|&gt; date (pstring "-")) .&gt;&gt;. (opt (skipChar ' ' &gt;&gt;. time)) .&gt;&gt; ws &gt;&gt;=? (fun ((a, b, c), tt) -&gt; let y, m, d = if a &gt; 12 then a, b, c else c, a, b let h, n = match tt with | Some((h, n), tt) -&gt; match tt with | Some true -&gt; (match h with 12 -&gt; h | _ -&gt; h + 12), n | Some false -&gt; (match h with 12 -&gt; h - 12 | _ -&gt; h), n | None -&gt; h, n | None -&gt; 0, 0 try preturn (System.DateTime(y, m, d, h, n, 0)) |&gt;&gt; DateTime with _ -&gt; fail "Invalid date/time format") </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload