C#

How to convert String to DateTime and DateTime to String

How to convert String to DateTime and DateTime to String
Share it:

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 it:

C#

Post A Comment:

0 comments: