Rob DiNardo - Web Development Tips

Home › Blogs › Rob's blog

Convert string to DateTime or output DateTime to string using .NET

Rob — December 1, 2010 - 20:14

I often times come across a situation where I have a string in a certain date time format and wish to convert that string into a .NET DateTime object for further manipulation.  In one recent situation, a date was supplied in an XML node (without a specified data type) as a string, but the output of the date had to be in a specific format for my client. 

Example:  We need to convert <submit_date>2010-12-04 13:22:32</submit_date> and output it as December 4, 2010 at 1:22 PM 

The trick lies within the DateTime.ParseExact() method provided by .NET.  Since we know that the date string is supplied in a certain format, namely “yyyy-MM-dd HH:mm:ss”, we can convert the supplied string into a DateTime .NET object then output in any format we wish.  Refer to this page for a list of Custom Date and Time Format Strings.

Here is a console application demonstrating how we would convert the string in the above example to DateTime, then output in desired format:

using System;
using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
           
            string newDate = ConvertDateTimeString("2010-12-04 13:22:34",
                                                    "yyyy-MM-dd HH:mm:ss",
                                                    "{0:MMMM d, yyyy} at {0:h:mm tt}");

            Console.WriteLine(newDate);

            Console.ReadLine();
        }


        public static string ConvertDateTimeString(string dateString, string dateStringFormat, string desiredFormat)
        {
            string output;
            try
            {
                DateTime MyDateTime = new DateTime();
                MyDateTime = DateTime.ParseExact(dateString, dateStringFormat, null);
                output = String.Format(desiredFormat, MyDateTime);
            }
            catch (FormatException)
            {
                output = String.Format("{0} is not in the correct format.", dateString);
            }
            return output;
        }
       
    }

The above will output...

December 4, 2010 at 1:22 PM

  • .NET
  • c#
  • coding
  • csharp
  • Reference
  • Rob's blog
  • Login to post comments

User login

  • Request new password

Code

  • WordPress Plugins