Neil.Allen
Neil.Allen

Reputation: 1636

C# Breaking up a DateTime with RegEx

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.

Upvotes: 2

Views: 182

Answers (5)

James Kyburz
James Kyburz

Reputation: 14453

You don't need regex for this you can use the DateTime.ToString(string) method ro extract what you want.

http://msdn.microsoft.com/en-us/library/zdtaw1bw

datetimevar.ToString("MM/dd");

Then you don't need to care about the locale as the output of ToString() with no arguments depends on your culture i.e the value differs...

Upvotes: 1

Sam Axe
Sam Axe

Reputation: 33738

how about datetime.ToString("MM/dd") ? or datetime.Month and datetime.Day

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564451

You can just use:

DateTimeVar.ToString("MM/dd");

There is no need for a custom method, as DateTime.ToString(string) already allows custom format strings for DateTime values.

Upvotes: 7

dmck
dmck

Reputation: 7861

Use the DateTimeVar.ToString("MM/dd") method.

For a full list of options you can pass to the ToString method check the Custom Date and Time Format Strings on MSDN

Upvotes: 2

Justin Pihony
Justin Pihony

Reputation: 67085

Why not just use the ToString(formatThatYouWant) override?

The code would be:

.ToString("MM/dd");

Remember, MSDN is your friend :)

Upvotes: 5

Related Questions