I have a value that is stored as a DateTime.
In order to make the output look more readable in an export, I would like to only have the MM/DD returned from the expression.
My current solution involves passing the DateTime as a string to a function which effectively chops it up into small pieces, and puts it back together again. While this works, I know that there must be a more effective/elegant solution.
My current code looks like this:
extractDate(DateTimeVar.ToString());
And the definition:
private string extractDate(string datetime)
{
string[] newString = datetime.Split(' ');
string newStringArray = newString[0];
string[] breakUp = newStringArray.Split('/');
string finalOutput = breakUp[0] + "/" + breakUp[1];
return finalOutput;
}
As you can see, quite messy. Another solution I came up with involved chopping off the first five characters, since a DateTime’s first 5 characters will always include “MM/dd”:
private string extractDate(string datetime)
{
return datetime.Substring(0, 5);
}
I would assume that the latter solution is a better one. However, is there one that is even better? Thanks.
You can just use:
There is no need for a custom method, as
DateTime.ToString(string)already allows custom format strings for DateTime values.