I have a Datetime object which I take from an XML file (closingDate).
I want to dynamically display all closingDates to the user. However, not all objects in the XML file necessarily contain a dateobject.
How can I do this (pseudocode):
DateTime closingDate = DateTime.Parse(xmlFile.selectSingleNode("Closing_Date")).toString();
and then later, I am writing out an HTML file with:
String fileListHTML += "<li><a href='#'>The file name gets put here</a> (Closed:
"+closingDate+")</li>";
Now, as long as there is a datetime, there is no issue. However, if there is no datetime object (ie: null), I get an error.
Can I somehow do an if statement to say (again, pseudo):
if (closingDate =="")
{
closingDate = "To be determined";
}
I am, of course, getting an error about casting a datetime to string.
Is there a way to do this?
I’m not a fan of turning
DateTimes tostrings until it is necessary.You could use a nullable DateTime. Use null to denote it’s not set or parsable. Alternatively scratch the nullable approach and use a sentinel such as
DateTime.MinValueinstead.This is untested but should get the point across:
I’d caution you to be careful about converting
DateTimeto strings without considerations to time zones and internationalization (for example,DateTime.Parse()can interpret dates very differently depending on regional settings and/or the culture you pass in).For simplicity, if you can control the format of the string, I’d suggest using UTC and the ISO 8601 format.