I have a string like this "10/13/2009 12:00:00 AM"
how can i convert it to YYYYMMDD format using c#
Date() function in R Language is used to convert a string into date format.
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);
}
}
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With