AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

How to convert String to DateTime and DateTime to String

By pushpam abhishek
Listen to this article

How to convert String to DateTime and DateTime to String

How to convert String to DateTime and DateTime to String

Converting from String to DateTime is not a trivial task as it requires some parsing. Fortunately .NET provides the DateTime.ParseExact method.


using System;
02.using System.Globalization;
03. 
04.public class MyClass
05.{
06.public static void Main()
07.{
08. 
09.string dateString, format;
10.DateTime dateTime;
11.CultureInfo cultureInfo = CultureInfo.CurrentCulture;
12. 
13.format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
14.// if format = "dd/MM/yyyy"
15.dateString = "01/03/1995";
16. 
17.try {
18.dateTime = DateTime.ParseExact(dateString, format, provider);
19.Console.WriteLine("{0} converts to {1}.", dateString, dateTime.ToString());
20.}
21.catch (FormatException) {
22.Console.WriteLine("{0} is not in the correct format.", dateString);
23.}
24.}
25.}
will output
1.01/03/1995 converts to 01/03/1995 00:00:00.
If one needs to convert this DateTime to a custom format like “dd.MM.YY” one would use the DateTime.ToString method:
01.using System;
02.using System.Globalization;
03. 
04.public class MyClass
05.{
06.public static void Main()
07.{
08. 
09.string dateString, format;
10.DateTime dateTime;
11.CultureInfo cultureInfo = CultureInfo.CurrentCulture;
12. 
13.format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
14.// if format = "dd/MM/yyyy"
15.dateString = "01/03/1995";
16.try {
17.dateTime = DateTime.ParseExact(dateString, format, cultureInfo);
18.Console.WriteLine("{0} converts to {1}.", dateString, dateTime.ToString());
19.dateString = dateTime.ToString("dd.MM.yy");
20.Console.WriteLine("converted to {0}.", dateString);
21.}
22.catch (FormatException) {
23.Console.WriteLine("{0} is not in the correct format.", dateString);
24.}
25. 
26.}
27.}
Output:

01/03/1995 converts to 01/03/1995 00:00:00.
.converted to 01.03.95.

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments