Three Approaches
- Convert.ToDateTime()
- DateTime.Parse() method
- DateTime.TryParse() method
using System;
namespace ConsoleStringDateToDate
{
class TestConvert
{
public void Test(string date) {
try
{
//by using Convert class
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Date: {0}",dt.ToString());
Console.WriteLine("Date 10 days before: {0}", dt.AddDays(-10).ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class TestParse
{
public void Test(string date)
{
try
{
//by using Parse
DateTime dt = DateTime.Parse(date);
Console.WriteLine("Date: {0}", dt.ToString());
Console.WriteLine("Date 10 days before: {0}", dt.AddDays(-10).ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class TestTryParse
{
public void Test(string date)
{
//by using TryParse
bool success = DateTime.TryParse(date, out DateTime dt);
if (success)
{
Console.WriteLine("Date: {0}", dt.ToString());
Console.WriteLine("Date 10 days before: {0}", dt.AddDays(-10).ToString());
}
else
{
Console.WriteLine("Invalid date format.");
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\nEXAMPLE: Convert class");
TestConvert tc = new TestConvert();
tc.Test("May 14, 2021");
tc.Test("May 14th, 2021");
Console.WriteLine("\nEXAMPLE: Parse method of DateTime struct");
TestParse tp = new TestParse();
tp.Test("May 14, 2021");
tp.Test("May 14th, 2021");
Console.WriteLine("\nEXAMPLE: TryParse method of DateTime struct");
TestTryParse tt = new TestTryParse();
tt.Test("May 14, 2021");
tt.Test("May 14th, 2021");
Console.ReadKey();
}
}
}
OUTPUT
EXAMPLE: Convert class
Date: 2021-05-14 12:00:00 AM
Date 10 days before: 2021-05-04 12:00:00 AM
The string was not recognized as a valid DateTime. There is an unknown word starting at index 6.
EXAMPLE: Parse method of DateTime struct
Date: 2021-05-14 12:00:00 AM
Date 10 days before: 2021-05-04 12:00:00 AM
The string was not recognized as a valid DateTime. There is an unknown word starting at index 6.
EXAMPLE: TryParse method of DateTime struct
Date: 2021-05-14 12:00:00 AM
Date 10 days before: 2021-05-04 12:00:00 AM
Invalid date format.
No comments:
Post a Comment