Convert Datetime to a Specified Format

Convert DateTime to a specified Format

Use DateTime.ParseExact, e.g.:

DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss", 
CultureInfo.InvariantCulture
).ToString("MMM. dd, yyyy HH:mm:ss")

How to convert DateTime to/from specific string format (both ways, e.g. given Format is yyyyMMdd)?

if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

Convert DateTime to a specific format

If you have a DateTime object you can convert it to a string with that particular format by using O as format specifier:

parsedDate.ToString("O")

or

parsedDate.ToUniversalTime().ToString("O") // if parsedDate is not UTC

returns "2015-03-26T18:02:58.1457980Z".


If the DateTimeKind of your DateTime object is not Utc then you won't get the Z extension at the end of the string according to ISO8601. In the example you provided the Z is present because DateTime.Parse will recognize it and return a DateTime in Utc. Should the Z be missing in the original string you parse you can still assume it's UTC by using ToUniversalTime() on the date time object.

Convert datetime to specified format in c#?

You can use DateTime.ParseExact as shown below:

DateTime.ParseExact("17/07/18 06:30:20", "yy/MM/dd HH:mm:ss", 
CultureInfo.InvariantCulture
).ToString("MMM. dd, yyyy HH:mm:ss");


Related Topics



Leave a reply



Submit