Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your code suggests that the variable may be either a date or a string that looks like a date. Dates you can simply return wit a cast, but strings must be parsed. Parsing comes with two caveats;</p> <ol> <li><p>if you aren't certain this string can be parsed, then use <code>DateTime.TryParse()</code>. </p></li> <li><p>Always include a reference to the culture you want to parse as. <code>ToShortDateString()</code> returns different outputs in different places. You will almost certainly want to parse using the same culture. I suggest this function dealing with both situations;</p> <pre><code>private DateTime ParseDateTime(object data) { if (data is DateTime) { // already a date-time. return (DateTime)data; } else if (data is string) { // it's a local-format string. string dateString = (string)data; DateTime parseResult; if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out parseResult)) { return parseResult; } else { throw new ArgumentOutOfRangeException("data", "could not parse this datetime:" + data); } } else { // it's neither a DateTime or a string; that's a problem. throw new ArgumentOutOfRangeException("data", "could not understand data of this type"); } } </code></pre></li> </ol> <p>Then call like this;</p> <pre><code>ParseDateTime(g[0]["MyUntypedDateField").ToShortDateString(); </code></pre> <p>Note that bad data throws an exception, so you'll want to catch that.</p> <p>Also; the 'as' operator does not work with the DateTime data type, as this only works with reference types, and DateTime is a value type.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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