tags:

views:

112

answers:

4

How can I convert DateTime "Thu Nov 30 19:00:00 EST 2006" to "11/30/2006"

A: 

DateTime.Parse() the string value than output to a custom format with dtVariable.ToString("custom string")

Josh Warner-Burke
+2  A: 
mydate.ToString("MM/dd/yyyy");

fixed the mm --> MM

Fredou
You mean `MM`. (Month, not minute)
SLaks
mm for minutes. There should be MM
Hun1Ahpu
+1  A: 
yourDate.ToString("d");
Hun1Ahpu
`d` specifies "Short Date Format", which depending on the locale, may not be `mm/dd/yyyy`
mlsteeves
@mlsteeves - You're right. But this is plus for globalization, isn't it?
Hun1Ahpu
@mlsteeves: Which, in most cases, is even better - you wouldn't want someone whose culture writes `dd/mm/yyyy` to see `mm/dd/yyyy`...
BlueRaja - Danny Pflughoeft
@BlueRaja Depends on what you are doing. If you are using an API that is expected mm/dd/yyyy, then 'd' might work during testing, but as soon as you go live, and it gets into an environment where 'd' != 'mm/dd/yyyy', then things start breaking.
mlsteeves
+7  A: 

Try something like this:

using System;
using System.Globalization;

class Example
{
    static void Main()
    {
        DateTime dateTime = DateTime.ParseExact("Thu Nov 30 19:00:00 EST 2006", 
            "ddd MMM dd HH:mm:ss EST yyyy", 
            CultureInfo.InvariantCulture);
        Console.WriteLine(dateTime.ToString("MM/dd/yyyy"));
    }
}

The .NET framework does not support time zone abbreviations so I hard-coded "EST" into the format string (just something to be aware of if you will need to parse strings from multiple time zones).

Andrew Hare
This is the only answer that will actually work.
SLaks
Cool... It works cool. Thanks a lot.
afin
Can you please share your idea that what should we do when given date contains other time zones?
afin