Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string to a date format

Tags:

c#

asp.net

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

how can i convert it to YYYYMMDD format using c#

like image 277
raklos Avatar asked Oct 14 '09 16:10

raklos


People also ask

Which function is used convert string into date format?

Date() function in R Language is used to convert a string into date format.


2 Answers

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);
    }
}
like image 177
Jon Skeet Avatar answered Oct 24 '22 09:10

Jon Skeet


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")
like image 33
Charles Bretana Avatar answered Oct 24 '22 09:10

Charles Bretana