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
How to Parse String with Hours Greater Than 24 to Timespan
How to Get Modified Date from File in C# on Windows Mobile
Accessing UI Controls in Task.Run with Async/Await on Winforms
How to Perform a Circular Bit Shift in C#
Update App.Config System.Net Setting at Runtime
How to Create a Generic Class from a String in C#
How to Print a Text File on Thermal Printer Using Printdocument
Is .Net 4.0 Compatible with Windows Xp Sp2 or Below
How to Remove Numbers from String Using Regex.Replace
Escape Quote in C# for JavaScript Consumption
Why Is Modulus Operator Not Working for Double in C#
Creating a Circularly Linked List in C#
How to Get the Icon from the Executable File Only Having an Instance of It's Process in C#
Accuracy of Textrenderer.Measuretext Results