5

I have a string like this "10/13/2009 12:00:00 AM"

how can i convert it to YYYYMMDD format using c#

5 Answers 5

12

Work out the two formats you want, then use:

DateTime dt = DateTime.ParseExact(input, inputFormat, 
                                  CultureInfo.InvariantCulture);
string output = dt.ToString(outputFormat, CultureInfo.InvariantCulture);

For example:

using System;
using System.Globalization;

class Test
{
    static void Main(string[] args)
    {
        string input = "10/13/2009 12:00:00 AM";
        string inputFormat = "MM/dd/yyyy HH:mm:ss tt";
        string outputFormat = "yyyyMMdd";
        DateTime dt = DateTime.ParseExact(input, inputFormat, 
                                          CultureInfo.InvariantCulture);
        string output = dt.ToString(outputFormat, CultureInfo.InvariantCulture);
        Console.WriteLine(output);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If your string is a valid datetime format that .Net can understand, all you need is:

   DateTime.Parse(yourString).ToString("yyyyMMdd")

EDITED: Many reasonable datetime formats are understandable by .Net without an explicit format specification, but if your specific one is not, then you will need to use an explicit format specifier.

   DateTime.ParseExact(yourString, format, 
         CultureInfo.InvariantCulture)).ToString("yyyyMMdd")

2 Comments

"C#" doesn't have any valid datetime formats - .NET has default formats that DateTime.Parse will accept, but they depend on the culture of the system. It's better to be explicit, IMO.
Edited to correct, but Jon, not being explicit has advantedge of being able to handle ALL the formats that .Net understands "out of the box", so to speak ... Depending on the scenario/requirements, I'd say each technique has it's place.
0
string s =  String.Format("{0:yyyyMMdd}", Convert.ToDateTime("10/13/2009 12:00:00 AM"));

1 Comment

That fails on my box - you're assuming that Convert.ToDateTime will handle that format, which it won't in a UK culture.
0

Those are pretty good solutions, but if you pass something in that does not match the pattern they will toss Exceptions. I like to use the SmartDate class from CSLA, http://www.lhotka.net/cslanet/download.aspx, myself. It deals with nulls and invalid values nicely. The TryStringToDate function is where the magic happens:

    private static bool TryStringToDate( string value, EmptyValue emptyValue, ref DateTime result )
    {
        DateTime tmp;
        if( String.IsNullOrEmpty( value ) )
        {
            if( emptyValue == EmptyValue.MinDate )
            {
                result = DateTime.MinValue;
                return true;
            }
            result = DateTime.MaxValue;
            return true;
        }
        if( DateTime.TryParse( value, out tmp ) )
        {
            result = tmp;
            return true;
        }
        string ldate = value.Trim().ToLower();
        if( ldate == "SmartDateT" ||
            ldate == "SmartDateToday" ||
            ldate == "." )
        {
            result = DateTime.Now;
            return true;
        }
        if( ldate == "SmartDateY" ||
            ldate == "SmartDateYesterday" ||
            ldate == "-" )
        {
            result = DateTime.Now.AddDays( -1 );
            return true;
        }
        if( ldate == "SmartDateTom" ||
            ldate == "SmartDateTomorrow" ||
            ldate == "+" )
        {
            result = DateTime.Now.AddDays( 1 );
            return true;
        }
        return false;
    }

So you should ultimately wind up with something like this:

        SmartDate dt = new SmartDate(input); 
        dt.FormatString = outputFormat;
        string output = dt.Text; 
        Console.WriteLine(output);

Comments

0

You could try something like this:

string myDate = "10/13/2009 12:00:00 AM";
DateTime result = new DateTime(DateTime.Now.Year, 1, 1);
DateTime.TryParse(myDate, out result);
string output = result.ToString("yyyyMMdd");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.